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

后端 未结 11 1421
[愿得一人]
[愿得一人] 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;
        }
    

提交回复
热议问题