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

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

    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.

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

    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

    0 讨论(0)
  • 2020-12-05 14:00

    add something like this to your code

      if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
      // IPv4 address
    
    0 讨论(0)
  • 2020-12-05 14:02

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

    Very Clean and sweet when using Linq

    IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()).Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray();
    
    0 讨论(0)
提交回复
热议问题