C#获取IP4或IP6协议的IP地址

原理,首先,要用System.Net.IPHostEntry把IP解析成IP实体,然后利用System.Net.IPAddress来解析IP列表,值得注意的是,IP4的IP地址,可以用AddressList[0]获取,IP6的IP地址,AddressList[1]获取

判断协议的方法,很简单,利用System.Net.Sockets.AddressFamily可以判断IP类型。


对于 IPv4,返回 System.Net.Sockets.AddressFamily.InterNetwork;对于 IPv6,返回 System.Net.Sockets.AddressFamily.InterNetworkV6

如图:


所以,可以用如下代码判断并获取正确的IP地址。


private IPAddress getIdAddress()
 {
  
     //IPHostEntry ipEntity = Dns.GetHostEntry(Dns.GetHostName());
     ////IPAddress ipAddr = ipEntity.AddressList[0];
  
     //IPAddress ipAddr = Dns.GetHostAddresses(Dns.GetHostName())[0];
     //if (ipAddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)//判断是否IP6协议
     //{
     //    ipAddr = Dns.GetHostEntry(Dns.GetHostName()).AddressList[1];
     //}
     IPAddress ipAddr = null;
     IPAddress [] arrIP = Dns.GetHostAddresses(Dns.GetHostName());
     foreach (IPAddress ip in arrIP)
     {
         if (System.Net.Sockets.AddressFamily.InterNetwork.Equals(ip.AddressFamily))
         {
             ipAddr = ip;
         }
         else if (System.Net.Sockets.AddressFamily.InterNetworkV6.Equals(ip.AddressFamily))
         {
             ipAddr = ip;
         }
     }
     return ipAddr;
 }

转载出处: http://hi.baidu.com/xiuyuanvip/item/153d02dba9b38bcb1a72b4db

你可能感兴趣的:(C#获取IP4或IP6协议的IP地址)