当前位置: 移动技术网 > IT编程>开发语言>c# > c#获取本机在局域网ip地址的二种方法

c#获取本机在局域网ip地址的二种方法

2019年07月18日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:/// <summary>/// 获取本机在局域网的ip地址/// </summary>/// <returns>&

复制代码 代码如下:

/// <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;
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网