How to get default NIC Connection Name

后端 未结 6 1630
刺人心
刺人心 2021-01-01 02:27

IMPORTANT EDIT: Back again on this subject. As you said there should be no default NIC, I\'m trying to understand if there is a way to detect all the NICs t

6条回答
  •  别那么骄傲
    2021-01-01 02:49

    This is a dirty way of doing it as it can be optimized by incorporating LINQ, etc

    using System.Net.NetworkInformation;
    
    List Interfaces = new List();
    foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
        {
            Interfaces.Add(nic);
        }
    }
    
    
    NetworkInterface result = null;
    foreach (NetworkInterface nic in Interfaces)
    {
        if (result == null)
        {
            result = nic;
        }
        else
        {
            if (nic.GetIPProperties().GetIPv4Properties() != null)
            {
                if (nic.GetIPProperties().GetIPv4Properties().Index < result.GetIPProperties().GetIPv4Properties().Index)
                    result = nic;
            }
        }
    }
    
    Console.WriteLine(result.Name);
    

    you'll probably want to tailor your results by using the results from nic.GetIPProperties() and nic.GetIPProperties().GetIPv4Properties()

提交回复
热议问题