Search code examples
c#ip-addressipv4

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


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() + "/";
        }
    }

Solution

  • add something like this to your code

      if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
      // IPv4 address