static private IReadOnlyList <PcapInterface> GetAllPcapInterfaces(IntPtr devicePtr, ICredentials credentials) { var list = new List <PcapInterface>(); var nics = NetworkInterface.GetAllNetworkInterfaces(); var nextDevPtr = devicePtr; while (nextDevPtr != IntPtr.Zero) { // Marshal pointer into a struct var pcap_if_unmanaged = new pcap_if_wrapper() { native = Marshal.PtrToStructure <pcap_if>(nextDevPtr) }; NetworkInterface networkInterface = null; foreach (var nic in nics) { // if the name and id match then we have found the NetworkInterface // that matches the PcapDevice if (pcap_if_unmanaged.GetNameString().EndsWith(nic.Id)) { networkInterface = nic; } } var pcap_if = new PcapInterface(pcap_if_unmanaged, networkInterface, credentials); list.Add(pcap_if); nextDevPtr = pcap_if_unmanaged.native.Next; } return(list); }
internal PcapInterface(pcap_if_wrapper pcapIf, NetworkInterface networkInterface, ICredentials credentials) { Name = pcapIf.GetNameString(); Description = pcapIf.GetDescriptionString(); Flags = pcapIf.native.Flags; Addresses = new List <PcapAddress>(); GatewayAddresses = new List <IPAddress>(); Credentials = credentials; // attempt to populate the mac address, // friendly name etc of this device if (networkInterface != null) { var ipProperties = networkInterface.GetIPProperties(); int gatewayAddressCount = ipProperties.GatewayAddresses.Count; if (gatewayAddressCount != 0) { foreach (GatewayIPAddressInformation gatewayInfo in ipProperties.GatewayAddresses) { GatewayAddresses.Add(gatewayInfo.Address); } } FriendlyName = networkInterface.Name; } // retrieve addresses var address = pcapIf.native.Addresses; while (address != IntPtr.Zero) { // Marshal memory pointer into a sockaddr struct var addr = Marshal.PtrToStructure <pcap_addr>(address); PcapAddress newAddress = new PcapAddress(addr); Addresses.Add(newAddress); // is this a hardware address? // if so we should set our MacAddress if (newAddress.Addr?.type == Sockaddr.AddressTypes.HARDWARE) { if (MacAddress == null) { MacAddress = newAddress.Addr.hardwareAddress; } else if (!MacAddress.Equals(newAddress.Addr.hardwareAddress)) { throw new InvalidOperationException("found multiple hardware addresses, existing addr " + MacAddress.ToString() + ", new address " + newAddress.Addr.hardwareAddress.ToString()); } } address = addr.Next; // move to the next address } }