and
and

Reputation: 87

Getting and checking local machine's ip address

I am trying to get IP address on local machine:

    private string GetIP()
    {

        string strHostName = "";
        strHostName = System.Net.Dns.GetHostName();

        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);


        IPAddress[] addr = ipEntry.AddressList;

        foreach (IPAddress ipaddr in addr)
        {
            if (ipaddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                return ipaddr.ToString();
        }

        return "IP error";                                   
    }

However I can't find a way to identify which interface is the one i need. For example:

enter image description here

I am lucky that the one i need is second in the list. But if it were in the back i would get IP of a wrong interface. How to check if I am getting IP for local area connection (or in general, the interface responsible for the connection).

Upvotes: 1

Views: 5309

Answers (2)

M.Babcock
M.Babcock

Reputation: 18965

You may be able to enumerate the network interfaces directly (rather than just their IPs) and filter then based on their interface type:

var interfaces = NetworkInterface.GetAllNetworkInterfaces()

And then filter it with something like:

interfaces.Where(ni => ni.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                       ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)

It may still return multiple network interfaces but it'll filter out at least some of them that you don't want. I use the above filter to get rid of loopback and virtual machine interfaces.

Then from there you can get the network interface's IP address using the IP properties.

In the spirit of brevity, once you determine which interface is the right one, you can get the IPv4 address (or at least one of them) of the interface using:

iface.GetIPProperties().UnicastAddresses.SingleOrDefault(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork);

Upvotes: 2

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

There is not method that return one address against the host name

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

it returns the local machine address for all the registered address in your DNS

So if in your DNS your machine has one name associated to one IP address it will return only that address otherwise it will return the list of addresses associated to that Host Name

you have to "filter" the list to understand what is your local address

Have a look at the below:

How to get the IP address of the server on which my C# application is running on?

Upvotes: 0

Related Questions