标签:
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 地址 } }
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 地址 } } } }
标签:
原文地址:http://www.cnblogs.com/shanranlei/p/5135715.html