C#winform程序获取本机IP地址
代码如下:
public static string GetLocalIp() { string ip = "1.1.1.1" ; try { string HostName = Dns.GetHostName(); //得到主机名 IPHostEntry IpEntry = Dns.GetHostEntry(HostName); for (int i = 0; i < IpEntry.AddressList.Length; i++) { //从IP地址列表中筛选出IPv4类型的IP地址 //AddressFamily.InterNetwork表示此IP为IPv4, //AddressFamily.InterNetworkV6表示此地址为IPv6类型 if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { ip = IpEntry.AddressList[i].ToString(); return ip; } } return ip; } catch (Exception ex) { MessageBox.Show("获取本机IP出错:" + ex.Message); return ip; } }