C#(winfrom)获得本机IP地址
2014-10-27 12:51
253 查看
最近在网上找C#如何获得本机局域网IP的代码,但是未能所愿,于是自己参照网上已有代码自己写了一段。思路是这样的,先获取所有IP集合,去除IPv6的地址,然后根据默认网关匹配IP,最后得到真正的局域网IP地址。
首先获得默认网关的代码(来源于网络)
然后是匹配默认网关和IP地址的,就是看是否在同一网段
然后是获得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的。
首先获得默认网关的代码(来源于网络)
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的。
相关文章推荐
- 获得真实IP地址及分析 (asp.net C#)
- C# 获得本地IP地址
- c#关于怎么获得IP地址
- 13 在C#中如何获得IP地址
- C#中IP地址的获得
- [.Net码农]C#获得本机的计算机名及IP地址
- C#通过域名获得IP地址的方法
- C# 通过url获得ip地址
- C#如何绕过代理服务器获得用户真实的IP地址呢?
- 如何获得客户端的ip地址?
- 用Visual C#获得计算机名称和IP地址
- 获得汉字字符串拼音首字母 C#版
- [转]如何用C++编程获得某台机器的IP地址
- Windows上获得IP地址的四种方法
- 在asp.net(C#)中怎么获得一个目录的大小?
- .NET中如何获得IP地址和主机名
- [j2se]利用JAVA获得IP地址的法子
- c# 获得局域网主机列表实例
- 如何用C++编程获得某台机器的IP地址?
- 如何用c#解析word(1)--获得文档中的style标签