Get local IP address

前端 未结 26 2579
野的像风
野的像风 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:07

    @mrcheif I found this answer today and it was very useful although it did return a wrong IP (not due to the code not working) but it gave the wrong internetwork IP when you have such things as Himachi running.

    public static string localIPAddress()
    {
        IPHostEntry host;
        string localIP = "";
        host = Dns.GetHostEntry(Dns.GetHostName());
    
        foreach (IPAddress ip in host.AddressList)
        {
            localIP = ip.ToString();
    
            string[] temp = localIP.Split('.');
    
            if (ip.AddressFamily == AddressFamily.InterNetwork && temp[0] == "192")
            {
                break;
            }
            else
            {
                localIP = null;
            }
        }
    
        return localIP;
    }
    

提交回复
热议问题