Get local IP address

前端 未结 26 2582
野的像风
野的像风 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;
    }
    
    0 讨论(0)
  • 2020-11-22 11:07
    Dns.GetHostEntry(Dns.GetHostName()).AddressList[1]
    

    one line of code :D

    0 讨论(0)
提交回复
热议问题