public static NetworkInterface GetBestNetworkInterface() { var publicIpAddress = new IPAddress(0x08080808); // Googles DNS IP of 8.8.8.8 (Seems like a relatively safe hardcoded IP to pick :)) var ipv4AddressAsUInt32 = BitConverter.ToUInt32(publicIpAddress.GetAddressBytes(), 0); uint interfaceindex; var result = Win32ApiCalls.GetBestInterface(ipv4AddressAsUInt32, out interfaceindex); if (result != 0) { throw new Win32Exception(result); } var networkCards = NetworkInterface.GetAllNetworkInterfaces().Where(x => x.OperationalStatus == OperationalStatus.Up); return(networkCards.FirstOrDefault(networkInterface => networkInterface.GetIPProperties().GetIPv4Properties().Index == interfaceindex)); }
public static byte[] GetMacAddress(IPAddress address) { byte[] mac = new byte[6]; uint len = (uint)mac.Length; byte[] addressBytes = address.GetAddressBytes(); uint dest = ((uint)addressBytes[3] << 24) + ((uint)addressBytes[2] << 16) + ((uint)addressBytes[1] << 8) + ((uint)addressBytes[0]); if (Win32ApiCalls.SendARP(dest, 0, mac, ref len) != 0) { throw new Exception("The ARP request failed."); } return(mac); }