Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 462
beta Avatar asked Dec 05 '12 14:12

beta


1 Answers

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

like image 192
Alex Filipovici Avatar answered Sep 27 '22 22:09

Alex Filipovici