日期:2014-05-18  浏览次数:20782 次

不同系统获取本地IP,求高手
C# code

    string registIp = "";
    string machineName = Environment.MachineName;
    string hostName = Dns.GetHostName();
    IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
    if (hostEntry.AddressList[0].AddressFamily.ToString() == "InterNetwork")
    {
        registIp = hostEntry.AddressList[0].ToString();
    }
    else if (hostEntry.AddressList[0].AddressFamily.ToString() == "InterNetworkV6")
    {
        registIp = hostEntry.AddressList[1].ToString();
    }


上面的貌似只能获取XP系统的本地IP,如果是WIN7那个IP就是一串奇怪的字母,还有如果是VISIT呢,求高手帮忙看看,要求不论在什么系统下,都能获取到本地IP。

------解决方案--------------------
那是 IPv6 的地址了,你这样写
C# code
string registIp = "";
string machineName = Environment.MachineName;
string hostName = Dns.GetHostName();
IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
for (int i = 0; i < hostEntry.AddressList.Length; i++)
{
    if (hostEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
    {
        registIp = hostEntry.AddressList[i].ToString();
        break;
    }
}

------解决方案--------------------
用tcp连接获取ip比较靠谱一点
C# code

System.Net.NetworkInformation.TcpConnectionInformation connection= Array.FindAll(
    System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(),
    o => !System.Net.IPAddress.IsLoopback(o.LocalEndPoint.Address)
).FirstOrDefault();
if (connection != null)
{
     string ip = connection.LocalEndPoint.Address.ToString();
}