我设法获得计算机中的所有NetworkInterface,然后我拒绝ipv6,环回,然后我最终有2个接口,一个是我想要使用的真正以太网,一个是我已经开放工作的VPN使用一些我不想使用的远程服务器。
C#中是否有任何方法可以识别它们?两者都为AddressFamily回答“InterNetwork”,并且都为NetworkingInterfaceType说“Ethernet”
有任何线索吗?
{
"items": [{
"id": 12345,
"name": "cool name",
"title": "title of the object",
"vendor": "vendor name"
}
这些是我最终拥有的两个接口:
答案 0 :(得分:2)
您可以找到连接到PCI总线的接口并从那里开始。这里有一些代码只返回PCI总线上的接口。
using System.Collections.Generic;
using System.Linq;
using System.Management; // Add a reference to System.Management for the project
using System.Net.NetworkInformation;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
HashSet<string> physicalMacAddresses = new HashSet<string>(GetMacAddressesOnPciBus());
var ifaces = NetworkInterface.GetAllNetworkInterfaces();
var physicalAddresses = ifaces
.Where(x => x.NetworkInterfaceType == NetworkInterfaceType.Ethernet
&& physicalMacAddresses.Contains(x.GetPhysicalAddress().ToString().Trim('{').Trim('}')));
}
private static IEnumerable<string> GetMacAddressesOnPciBus()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select MACAddress,PNPDeviceID FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND PNPDeviceID IS NOT NULL");
ManagementObjectCollection mObject = searcher.Get();
foreach (ManagementObject obj in mObject)
{
string pnp = obj["PNPDeviceID"].ToString();
if (pnp.Contains("PCI\\"))
{
string mac = obj["MACAddress"].ToString();
mac = mac.Replace(":", string.Empty);
yield return mac;
}
}
}
}
}
查找MAC地址的技术来自此处how-to-determine-mac-address-of-the-actual-physical-network-card-not-virtual。
答案 1 :(得分:0)
List<IPAddress> localIPs = new List<IPAddress>();
var ifaces = NetworkInterface.GetAllNetworkInterfaces();
//I'm working on unity and it does not allow me to do .ToList().. for some reason.
List<NetworkInterface> IfacesList = new List<NetworkInterface>();
foreach (var i in ifaces)
IfacesList.Add(i);
var selected = IfacesList.FindAll(x => x.NetworkInterfaceType == NetworkInterfaceType.Ethernet);
if (selected.Count == 1)
{
var addresses = selected[0].GetIPProperties().UnicastAddresses;
//once again, cannot use .toList()
List<UnicastIPAddressInformation> addressesList = new List<UnicastIPAddressInformation>();
foreach (var address in addresses)
addressesList.Add(address);
var ip = addressesList.Find(x => x.Address.AddressFamily == AddressFamily.InterNetwork).Address;
//return new IPEndPoint(ip, 1);
}
else
{
//HERE I need to differentiate my IP from VPN IP
var addresses = selected[1].GetIPProperties().UnicastAddresses;
IPAddress ip = addresses[0].Address;
var ipAddress = ip.ToString();
}