Get local IP address

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

    There is already many of answer, but I m still contributing mine one:

    public static IPAddress LocalIpAddress() {
        Func localIpPredicate = ip =>
            ip.AddressFamily == AddressFamily.InterNetwork &&
            ip.ToString().StartsWith("192.168"); //check only for 16-bit block
        return Dns.GetHostEntry(Dns.GetHostName()).AddressList.LastOrDefault(localIpPredicate);
    }
    

    One liner:

    public static IPAddress LocalIpAddress() => Dns.GetHostEntry(Dns.GetHostName()).AddressList.LastOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork && ip.ToString().StartsWith("192.168"));
    

    note: Search from last because it still worked after some interfaces added into device, such as MobileHotspot,VPN or other fancy virtual adapters.

提交回复
热议问题