C#获取本地IP地址兼容win7和xp

来源:互联网 发布:淘宝上便宜的零食店铺 编辑:程序博客网 时间:2024/04/28 17:13

获取本机ip本来是很容易的,IPAddress _ip = Dns.GetHostAddresses(Dns.GetHostName())[0];就行了

但是在vista win7等系统里面这样获得的是ipv6地址,


  1. private string GetLocalIp()  
  2. {  
  3.    string localIp;  
  4.    IPHostEntry host;  
  5.    host = Dns.GetHostEntry(Dns.GetHostName());  
  6.    if (host.AddressList.Length > 1)  
  7.    {  
  8.       //win7 ip 这里或许要用length  
  9.       localIp = host.AddressList[1].ToString();  
  10.    }  
  11.    else  
  12.    {  
  13.       //xp  
  14.       localIp = host.AddressList[0].ToString();  
  15.    }  
  16.   
  17.    return localIp;  
  18.   
  19. }  
0 0
原创粉丝点击