Get local IP address

前端 未结 26 2589
野的像风
野的像风 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 10:42

    Refactoring Mrcheif's code to leverage Linq (ie. .Net 3.0+). .

    private IPAddress LocalIPAddress()
    {
        if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
        {
            return null;
        }
    
        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
    
        return host
            .AddressList
            .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
    }
    

    :)

提交回复
热议问题