C#获取本机IP且过滤非真实网卡(如虚拟机网卡)
参考了网上的文章,具体地址不记得了。
下面的方法可以过滤掉虚拟机的网卡等无效网卡,进而只留下真实的网卡。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; namespace _15获取本机IP_过滤非真实网卡_ { class Program { static void Main(string[] args) { List<string> listIP = new List<string>(); ManagementClass mcNetworkAdapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc_NetworkAdapterConfig = mcNetworkAdapterConfig.GetInstances(); foreach (ManagementObject mo in moc_NetworkAdapterConfig) { string mServiceName = mo["ServiceName"] as string; //过滤非真实的网卡 if (!(bool)mo["IPEnabled"]) { continue; } if (mServiceName.ToLower().Contains("vmnetadapter") || mServiceName.ToLower().Contains("ppoe") || mServiceName.ToLower().Contains("bthpan") || mServiceName.ToLower().Contains("tapvpn") || mServiceName.ToLower().Contains("ndisip") || mServiceName.ToLower().Contains("sinforvnic")) { continue; } //bool mDHCPEnabled = (bool)mo["IPEnabled"];//是否开启了DHCP //string mCaption = mo["Caption"] as string; //string mMACAddress = mo["MACAddress"] as string; string[] mIPAddress = mo["IPAddress"] as string[]; //string[] mIPSubnet = mo["IPSubnet"] as string[]; //string[] mDefaultIPGateway = mo["DefaultIPGateway"] as string[]; //string[] mDNSServerSearchOrder = mo["DNSServerSearchOrder"] as string[]; //Console.WriteLine(mDHCPEnabled); //Console.WriteLine(mCaption); //Console.WriteLine(mMACAddress); //PrintArray(mIPAddress); //PrintArray(mIPSubnet); //PrintArray(mDefaultIPGateway); //PrintArray(mDNSServerSearchOrder); if (mIPAddress != null) { foreach (string ip in mIPAddress) { if (ip != "0.0.0.0") { listIP.Add(ip); } } } mo.Dispose(); } PrintList(listIP); Console.WriteLine("-- -- The End -- --"); Console.ReadKey(); } static void PrintList<T>(List<T> list) { foreach(T item in list) { Console.WriteLine(item); } } static void PrintArray<T>(T[] list) { foreach (T item in list) { Console.WriteLine(item); } Console.WriteLine(); } } }
如果你觉得这篇文章对你有帮助或者使你有所启发,请点击右下角的推荐按钮,谢谢,:)