码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2016-01-16 18:58:38      阅读:528      评论:0      收藏:0      [点我收藏+]

标签:

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筛选

 

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

标签:

原文地址:http://www.cnblogs.com/shanranlei/p/5135715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!