问题描述
一台电脑有IPV4地址和IPV6地址,目前使用的基本是IPV4地址, 有些情况还有多个网卡,有线的、无线的、还有vmare虚拟的两个网卡。获取所有的IP地址
//获取本机IP string HostName = Dns.GetHostName(); IPHostEntry IpEntry = Dns.GetHostEntry(HostName); //得到主机IP IPAddress[] addresslIst = IpEntry.AddressList;//得到本机所有的IP地址
获取IPv4协议的ip地址
string HostName = Dns.GetHostName(); IPHostEntry IpEntry = Dns.GetHostEntry(HostName); //得到主机IP IPAddress[] addresslIst = IpEntry.AddressList; for (int i = 0; i < addresslIst.Length; i++) { //从IP地址列表中筛选出IPv4类型的IP地址 //AddressFamily.InterNetwork表示此IP为IPv4, //AddressFamily.InterNetworkV6表示此地址为IPv6类型 if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { IPAddress ipAddress = IpEntry.AddressList[i]; Console.WriteLine("ipAddress = " + ipAddress.ToString()); break; } } Console.ReadKey();
上面的代码解决了只有一个网卡的情况下获取IPV4地址的问题,多网卡问题并未解决