30

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() + "/";
        }
    }
Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
John Ryann
  • 2,283
  • 11
  • 43
  • 60

11 Answers11

36

From my blog:

/// <summary> 
/// This utility function displays all the IP (v4, not v6) addresses of the local computer. 
/// </summary> 
public static void DisplayIPAddresses() 
{ 
    StringBuilder sb = new StringBuilder(); 

    // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection) 
    NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); 

    foreach (NetworkInterface network in networkInterfaces) 
    { 
        // Read the IP configuration for each network 
        IPInterfaceProperties properties = network.GetIPProperties(); 

        // Each network interface may have multiple IP addresses 
        foreach (IPAddressInformation address in properties.UnicastAddresses) 
        { 
            // We're only interested in IPv4 addresses for now 
            if (address.Address.AddressFamily != AddressFamily.InterNetwork) 
                continue; 

            // Ignore loopback addresses (e.g., 127.0.0.1) 
            if (IPAddress.IsLoopback(address.Address)) 
                continue; 

            sb.AppendLine(address.Address.ToString() + " (" + network.Name + ")"); 
        } 
    } 

    MessageBox.Show(sb.ToString()); 
}

In particular, I do not recommend Dns.GetHostAddresses(Dns.GetHostName());, regardless of how popular that line is on various articles and blogs.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 2
    I was having such a hard time getting correct results with Dns..... This provided me exactly what I was looking for. Thanks – Tsukasa Jun 13 '13 at 20:03
  • 1
    had trouble before with website hosted in Azure. This however works pretty well, as opposed to the Dns.GetHostAddress method you mentioned – Tudor Carean Jun 16 '15 at 09:01
28

add something like this to your code

  if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
  // IPv4 address
Joost Evertse
  • 1,065
  • 7
  • 8
12

Here's a function I use:

public static string GetIP4Address()
{
    string IP4Address = String.Empty;

    foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
    {
        if (IPA.AddressFamily == AddressFamily.InterNetwork)
        {
            IP4Address = IPA.ToString();
            break;
        }
    }

    return IP4Address;
}

As an enumerable:

public static IEnumerable<string> GetIP4Addresses()
{
    return Dns.GetHostAddresses(Dns.GetHostName())
        .Where(IPA => IPA.AddressFamily == AddressFamily.InterNetwork)
        .Select(x => x.ToString());
}
Joe
  • 80,724
  • 18
  • 127
  • 145
  • 1
    I would not recommend comparing against a string since this needs a lookup of the enum value via reflection and perform a string comparison. Especially since you can compare against the enum `AddressFamily.InterNetwork` without problem. – Alex Jul 12 '11 at 18:06
  • This function returns one address, but the question states it must support hosts with multiple IPv4 addresses. – Greg Bacon Mar 05 '13 at 13:57
7

Very Clean and sweet when using Linq

IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()).Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray();
electricalbah
  • 2,227
  • 2
  • 22
  • 36
4

Write locaIPs.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
4

From MSDN on Dns.GetHostAddresses,

When an empty string is passed as the host name, this method returns the IPv4 addresses of the local host for all operating systems except Windows Server 2003; for Windows Server 2003, both IPv4 and IPv6 addresses for the local host are returned.

IPv6 addresses are filtered from the results of the GetHostAddresses method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty IPAddress instance if only IPv6 results where available for the hostNameOrAddress.parameter.

So, you can use this to try and parse it:

IPAddress.TryParse

then check AddressFamily which

Returns System.Net.Sockets.AddressFamily.InterNetwork for IPv4 or System.Net.Sockets.AddressFamily.InterNetworkV6 for IPv6.

string input = "192.168.0.10";

IPAddress address;
if (IPAddress.TryParse(input, out address))
{
    switch (address.AddressFamily)
    {
        case System.Net.Sockets.AddressFamily.InterNetwork:
            // we have IPv4
            break;
        case System.Net.Sockets.AddressFamily.InterNetworkV6:
            // we have IPv6
            break;
        default:
            // do something else
            break;
    }
}
1

I used the answer that started with

/// <summary> and it mostly worked:
//for some reason Visual Studio 2010 did not understand AddressFamily.Inernetwork
    if (address.Address.AddressFamily != AddressFamily.InterNetwork) 

I had to use:

if(address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)

but I actually used:

if(!address.Address.AddressFamily.Equals(System.Net.Sockets.AddressFamily.InterNetwork))

Also, I added:

if (network.OperationalStatus != OperationalStatus.Up)
                continue;

Because there were some networks which didn't work and should never have been there, I did see that they were in the registry. ---Alvin

Farhan S.
  • 698
  • 8
  • 26
dulcana
  • 49
  • 5
0

For me the cleaner solution would be:

 public static string GetLocalIP() 
        {
            string ipv4Address = String.Empty;

            foreach (IPAddress currentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (currentIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ipv4Address = currentIPAddress.ToString();
                    break;
                }
            }

            return ipv4Address;
        }
Farhan S.
  • 698
  • 8
  • 26
svives
  • 82
  • 3
  • This function returns one address, but the question states it must support hosts with multiple IPv4 addresses. – Greg Bacon Mar 05 '13 at 13:57
0

I use this helper method that returns the first active IPV4 address after filtering out the IPV6 and Loopback once


    public static IPAddress GetLocalIPAddress()
    {
        IPAddress result = null;
        IPHostEntry iphostentry = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress[] ipv4Address = Array.FindAll(iphostentry.AddressList, add => add.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(add));
        if (ipv4Address.Length > 0 )
        {
            result =ipv4Address[0];
        }
        return result;
    }
Bedasso
  • 1,652
  • 1
  • 14
  • 17
0

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;
}
Kim Ki Won
  • 1,795
  • 1
  • 22
  • 22
0

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;
            }                
        }
Farid
  • 33
  • 3