How to get the IP address of the network adapter used to access the Internet

I am wondering if there is a reliable way to find the IPv4 address of the network adapter on my computer that is used to access the Internet (since this is the one to which I would like to bind my server). I used to get a list of local IP addresses:

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 in this list of addresses, but the third (since I had 2 virtual machines, and both of them created a virtual adapter).

Any advice would be highly appreciated.

+4
source share
1 answer
 IPAddress ip = System.Net.Dns.GetHostEntry(Environment.MachineName).AddressList.Where(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault(); 

Alternatively you can 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 need to replace "Local Area Connection" with the name of your adapter in Control Panel\Network and Internet\Network Connections

+6
source

All Articles