C# 获取本机局域网真实ip,排除虚拟网卡
经过研究发现虚拟网卡应该是没有默认网关的,而且虚拟网卡的mac地址也有规律,所以根据默认网关和mac地址来进行判断是否为虚拟网卡
public static List<string> GetLocalIP()
{
List<string> IpList = new List<string>();
List<string> AllIpList = new List<string>();
try
{
foreach (var item in Dns.Resolve(Dns.GetHostName()).AddressList)
{
AllIpList.Add(item.ToString());
}
if (AllIpList.Count() == 1)
{
IpList.Add(AllIpList[0].ToString());
return IpList;
}
else if (AllIpList.Count() == 0)
{
return IpList;
}
//当存在多个网卡时,判断哪个ip是物理网卡的ip
else
{
//虚拟网卡mac地址的前6位
string[] vmwareList = new string[] { "000569", "000C29", "005056", "001c14", "001C42", "0003FF", "000F4B", "00163E", "080027" };
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection nics = mc.GetInstances();
foreach (ManagementObject nic in nics)
{
try
{
if (Convert.ToBoolean(nic["ipEnabled"]) == true)
{
foreach (var item in (nic["IPAddress"] as String[]))
{
if (AllIpList.Contains(item))
{
if (nic["DefaultIPGateway"] != null && (nic["DefaultIPGateway"] as String[]).Length > 0)//判断当前网卡是否存在默认网关
{
string mac = nic["MacAddress"].ToString().Replace(":", "").Replace("-", "");
if (!string.IsNullOrEmpty(mac) && mac.Length > 6)
{
mac = mac.Substring(0, 6);
if (!vmwareList.Contains(mac))//判断当前网卡的mac是否为虚拟网卡的mac
{
IpList.Add(item);
return IpList;
}
}
}
}
}
}
}
catch (Exception)
{
}
}
}
}
catch
{
return IpList;
}
return IpList;
}