Get local IP address

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

    To get local Ip Address:

    public static string GetLocalIPAddress()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        throw new Exception("No network adapters with an IPv4 address in the system!");
    }
    

    To check if you're connected or not:

    System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

提交回复
热议问题