IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
string myip = IpEntry.AddressList[0].ToString();
但是如果安装了IPV6,就取得的是IPV6的IP地址.
string myip = IpEntry.AddressList[1].ToString();
这样就在IPV6的情况下取得IPV4的IP地址.
string myHostName = Dns.GetHostName();
string myHostIP = "ip",ipv4="";
for (int i = 0; i < 10; i++)
{
try
{
myHostIP = Dns.GetHostEntry(myHostName).AddressList[i].ToString();
if (myHostIP.Contains('.')) ipv4=myHostIP;break;
}
catch { break; }
}
第一种:
private void GetIP()
{
string hostName = Dns.GetHostName();//本机名
//System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期,我运行时且只返回了一个IPv4的地址
System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//会返回所有地址,包括IPv4和IPv6
foreach (IPAddress ip in addressList)
{
listBox1.Items.Add(ip.ToString());
}
}
第二种:
static string GetLocalIp()
{
string hostname = Dns.GetHostName();//得到本机名
//IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已过期,只得到IPv4的地址
IPHostEntry localhost = Dns.GetHostEntry(hostname);
IPAddress localaddr = localhost.AddressList[0];
return localaddr.ToString();
}
第三种:
string strUrl = "提供IP查询的网站的链接";
Uri uri = new Uri(strUrl);
WebRequest webreq = WebRequest.Create(uri);
Stream s = webreq .GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.Default);
string all = sr.ReadToEnd();
int i = all.IndexOf("[") + 1;
//分析字符串得到IP
return ip;
/*
我用的是http://www.ip.cn/getip.php?action=getip&ip_url=&from=web
(这种链接很容易找的,百度“IP”得到一些网站,分析一下网站的链接就能得到)
返回的数据是:
当前 IP:0.0.0.0
来自:XX省XX市 电信
GeoIP: Beijing, China