c#获取本机在局域网ip地址的二种方法
程序员文章站
2024-02-25 23:39:27
复制代码 代码如下:/// /// 获取本机在局域网的ip地址/// /// &...
复制代码 代码如下:
/// <summary>
/// 获取本机在局域网的ip地址
/// </summary>
/// <returns></returns>
private string getlocalipaddress()
{
system.net.ipaddress[] addresslist = dns.gethostentry(dns.gethostname()).addresslist;
string strnativeip = "";
string strserverip = "";
if (addresslist.length > 1)
{
strnativeip = addresslist[0].tostring();
strserverip = addresslist[1].tostring();
}
else if(addresslist.length==1)
{
strserverip = addresslist[0].tostring();
}
return strserverip;
}
另外一种就是抓取网页中查询到的上网地址的ip来实现的。实现如下:
复制代码 代码如下:
/// <summary>
/// 获取本机的上网ip
/// </summary>
/// <returns></returns>
private string getconnectnetaddress()
{
string strurl = "http://www.ip138.com/ip2city.asp"; //获得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(); //读取网站返回的数据 格式:您的ip地址是:[x.x.x.x]
int i = all.indexof("[") + 1;
string tempip = all.substring(i, 15);
string ip = tempip.replace("]", "").replace(" ", "").replace("<", "");
return ip;
}
上一篇: java右下角弹窗示例分享