获得IP地址

2014-08-04  籽藤 

更新了一个获得IP地址的方法。之前的方法不适用虚拟机,得不到虚拟机的地址,只得返回127.0.0.1

引用: http://stackoverflow.com/questions/1599025/get-ip-of-my-machine-c-sharp-with-virtual-machine-installed

之前的方式

IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName()); string myip = GetIpv4(IpEntry.AddressList); private static string GetIpv4(IPAddress[] iPAddress) { string ipv4 = ""; if (iPAddress != null) foreach (IPAddress ipadd in iPAddress) { if (ipadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) ipv4 = ipadd.ToString(); } return ipv4; }

现在的方式

private string GetIpv4() { NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces(); var network = networks.Where(n => n.Name.Contains("Local Area Connection")).First(); IPInterfaceProperties ipProp = network.GetIPProperties(); UnicastIPAddressInformation ucip = ipProp.UnicastAddresses[ipProp.UnicastAddresses.Count - 1]; return ucip.Address.ToString(); }
339°/3399 人阅读/0 条评论 发表评论

登录 后发表评论