How to get default NIC Connection Name

后端 未结 6 1676
刺人心
刺人心 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:47

    using System.Linq;
    using System.Net.NetworkInformation;
    
    var nic = NetworkInterface
         .GetAllNetworkInterfaces()
         .FirstOrDefault(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback && i.NetworkInterfaceType != NetworkInterfaceType.Tunnel);
    var name = nic.Name;
    

    or more elegant solution:

    .Where(i => !(
        new[] { NetworkInterfaceType.Loopback, NetworkInterfaceType.Tunnel }
        .Contains(i.NetworkInterfaceType)))
    

    or if you want to practice in LINQ:

    static IEnumerable GetAllNetworkInterfaces(IEnumerable excludeTypes)
    {
        var all = NetworkInterface.GetAllNetworkInterfaces();
        var exclude = all.Where(i => excludeTypes.Contains(i.NetworkInterfaceType));
        return all.Except(exclude);
    }
    

    Usage:

    var nic = GetAllNetworkInterfaces(new[] { NetworkInterfaceType.Tunnel, NetworkInterfaceType.Loopback });
    

提交回复
热议问题