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

来源:互联网 发布:淘宝店铺智能版有用吗 编辑:程序博客网 时间:2024/04/29 08:03

最近在网上找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的。


0 0