首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

不同系统获取本地IP,求高手解决方法

2012-06-12 
不同系统获取本地IP,求高手C# codestring registIp string machineName Environment.MachineNames

不同系统获取本地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();} 

热点排行