beta
beta

Reputation: 2633

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

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.

Upvotes: 6

Views: 14169

Answers (1)

Alex Filipovici
Alex Filipovici

Reputation: 32581

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

Upvotes: 9

Related Questions