日期:2014-05-18 浏览次数:20814 次
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(); }
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比较靠谱一点
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(); }