I'm wondering if there's a reliable way of finding the IPv4 address of the network adapter in my machine which is used to access the internet (since this is the one I'd like to bind my server to). I used to get a list of local ip addresses like this:
IPAddress ip = System.Net.Dns.GetHostByName(Environment.MachineName).AddressList[0];
And it worked fine but today it failed because the IP address I was looking for was not the first one in this address list but the 3rd one (since I had 2 virtual machines running and both of these created a virtual adapter).
Any advice would be much appreciated.
IPAddress ip = System.Net.Dns.GetHostEntry(Environment.MachineName).AddressList.Where(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault();
As an alternative way, you could use:
using System.Net.NetworkInformation;
//...
var local = NetworkInterface.GetAllNetworkInterfaces().Where(i => i.Name == "Local Area Connection").FirstOrDefault();
var stringAddress = local.GetIPProperties().UnicastAddresses[0].Address.ToString();
var ipAddress = IPAddress.Parse(stringAddress);
where you just have to replace the "Local Area Connection"
with the name of your adapter in the Control Panel\Network and Internet\Network Connections
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With