您的位置:首页 > 编程语言 > C#

C#(winfrom)获得本机IP地址

2014-10-27 12:51 253 查看
最近在网上找C#如何获得本机局域网IP的代码,但是未能所愿,于是自己参照网上已有代码自己写了一段。思路是这样的,先获取所有IP集合,去除IPv6的地址,然后根据默认网关匹配IP,最后得到真正的局域网IP地址。

首先获得默认网关的代码(来源于网络)

public static string gateway(){
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
IPInterfaceProperties adapterProperties = adapters[0].GetIPProperties();
GatewayIPAddressInformationCollection gateway = adapterProperties.GatewayAddresses;
string gateway_2 = gateway[0].Address.ToString();           //from internet
return gateway_2;
}

然后是匹配默认网关和IP地址的,就是看是否在同一网段

public static bool isz(string a,string b) {
string[] sArray1 = a.Split('.');
string[] sArray2 = b.Split('.');
for (int i=0;i!=3;i++)
{
if (sArray1[i] != sArray2[i]) return false;
}
return true;
}


然后是获得IP地址的

public static string getip() {
IPAddress[] _ips = Dns.GetHostAddresses(Dns.GetHostName());
string _gateway= mynet.gateway();
foreach (IPAddress _ip in _ips)
{
if (!_ip.IsIPv6LinkLocal && mynet.isz(_gateway,_ip.ToString())) { return _ip.ToString(); }
}
return "0.0.0.0";
}

为了方便,全写成了static的。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# C#IP