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

后端 未结 11 1308
[愿得一人]
[愿得一人] 2020-12-05 13:23

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 m

相关标签:
11条回答
  • 2020-12-05 14:07

    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;
        }
    
    0 讨论(0)
  • 2020-12-05 14:11

    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());
    }
    
    0 讨论(0)
  • 2020-12-05 14:11

    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;
            }
    
    0 讨论(0)
  • 2020-12-05 14:12

    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;
                }                
            }
    
    0 讨论(0)
  • 2020-12-05 14:13

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

    0 讨论(0)
提交回复
热议问题