潸然泪下的小飞飞

导航

C# 获取本机指定类型指定网卡的Ip地址

1.简单方式 ,适用于单网卡

  string hostName = Dns.GetHostName();
            IPAddress[] addresses = Dns.GetHostAddresses(hostName);
            foreach (IPAddress address in addresses)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    //本机IPV4 地址
                }
                else if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    //本机IPV6 地址
                }
            }
单网卡区分IPV4与IpV6

2.终极方法,使用多网卡,不限制网卡类型

 string ipv4 = "";
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                //Wireless80211 无线网卡     Ethernet 以太网卡   
                if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {

                    //网卡Mac地址
                    System.Net.NetworkInformation.PhysicalAddress mac = adapter.GetPhysicalAddress();
                    //TODO:根据mac 地址 匹配目标网卡

                    //获取以太网卡网络接口信息
                    IPInterfaceProperties ip = adapter.GetIPProperties();
                    //获取单播地址集
                    UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                    foreach (UnicastIPAddressInformation ipadd in ipCollection)
                    {
                        if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                       {
                            ipv4= ipadd.Address.ToString();//获取ip
                        }
                        else if (ipadd.Address.AddressFamily == AddressFamily.InterNetworkV6)
                        {
                            //本机IPV6 地址
                        }
                    }
                }
            }
支持网卡类型 网卡mac筛选

 

posted on 2016-01-16 16:19  潸然泪  阅读(2275)  评论(1编辑  收藏  举报