获取本地主机IP地址

时间:2014-04-17 09:04:35

标签: c# ip

public static string GetLocalIpAddress()
    {
        string hostName = Dns.GetHostName();
        IPHostEntry ip = Dns.GetHostEntry(hostName);
        string IpAddress = Convert.ToString(ip.AddressList[2]);
        return IpAddress.ToString();
    }

这有时会显示Index out of bound of exception 它应该是什么问题。 提前谢谢

3 个答案:

答案 0 :(得分:7)

尝试这种方法,它对我有用。

 public static string GetIPAddress()
    {
        IPHostEntry host;
        string localIP = "?";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
            }
        }
        return localIP;
    }

谢谢,

答案 1 :(得分:1)

foreach (var addr in Dns.GetHostEntry(string.Empty).AddressList)
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
Console.WriteLine("IPv4 Address: {0}", addr)
}

答案 2 :(得分:0)

他们以前回答过。你应该在地址列表上查看你的长度。因为它不会总是2。

这里有关于stackoverflow的另一个答案: Getting valid IP from IPHostEntry

相关问题