Get local IP address

前端 未结 26 2872
野的像风
野的像风 2020-11-22 10:07

In the internet there are several places that show you how to get an IP address. And a lot of them look like this example:

String strHostName = string.Empty;         


        
26条回答
  •  天涯浪人
    2020-11-22 11:02

    Tested with one or multiple LAN cards and Virtual machines

    public static string DisplayIPAddresses()
        {
            string returnAddress = String.Empty;
    
            // 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();
    
                if (network.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
                       network.OperationalStatus == OperationalStatus.Up &&
                       !network.Description.ToLower().Contains("virtual") &&
                       !network.Description.ToLower().Contains("pseudo"))
                {
                    // 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;
    
                        returnAddress = address.Address.ToString();
                        Console.WriteLine(address.Address.ToString() + " (" + network.Name + " - " + network.Description + ")");
                    }
                }
            }
    
           return returnAddress;
        }
    

提交回复
热议问题