How do I determine the local host’s IPv4 addresses?

Viewed 68672

How do I get only Internet Protocol version 4 addresses from Dns.GetHostAddresses()? I have the code below, and it gives me IPv4 and IPv6 addresses. I have to make it work with boxes that have multiple IPv4 addresses.

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
private void get_IPs()
    {
        foreach (IPAddress a in localIPs)
        {
           server_ip = server_ip + a.ToString() + "/";
        }
    }
11 Answers

Very Clean and sweet when using Linq

IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()).Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray();

This is my code. And can find it on many LAN cards.

private string GetLocalIpAddress()
{
    string localIpAddress = string.Empty;
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

    foreach (NetworkInterface nic in nics)
    {
        if (nic.OperationalStatus != OperationalStatus.Up)
        {
            continue;
        }

        IPv4InterfaceStatistics adapterStat = (nic).GetIPv4Statistics();
        UnicastIPAddressInformationCollection uniCast = (nic).GetIPProperties().UnicastAddresses;

        if (uniCast != null)
        {
            foreach (UnicastIPAddressInformation uni in uniCast)
            {
                if (adapterStat.UnicastPacketsReceived > 0
                    && adapterStat.UnicastPacketsSent > 0
                    && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                {
                    if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        localIpAddress = nic.GetIPProperties().UnicastAddresses[0].Address.ToString();

                        break;
                    }
                }
            }
        }
    }

    return localIpAddress;
}

Here is a code to find the first connected IPv4 by using for loop :

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

        for (int i=0 ; i<localIPs.Length ; i++)
        {
            if (localIPs[i].AddressFamily == AddressFamily.InterNetwork)
            {
                ipAddress = localIPs[i];
                break;
            }                
        }
Related