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

后端 未结 11 1376
[愿得一人]
[愿得一人] 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 13:58

    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;
        }
    }
    

提交回复
热议问题