Determine which network adapter has the highest priority in C#? - c#

If we have multiple network interfaces with the same DNS suffix on a given machine, how do I programatically determine which network interface traffic will be routed over?
For example, I am connected to my companies network via ethernet in office, and connected to the companies network via VPN from inside the office. This sounds stupid, but with the way our networks are connected, if the internal link to our datacenter goes down - I VPN from inside the office to continue development.
Our software has logic to determine our "local ip address" and uses that for authentication logic elsewhere. I know from practice that all my traffic is routed over the VPN when connected - but am struggling with what the correct implementation in code is for robustly choosing the IP address of the adapter with the highest priority.
What I have right now is:
var unicastIpAddressInformation = NetworkInterface.GetAllNetworkInterfaces()
.Where(nic => nic.OperationalStatus == OperationalStatus.Up
&& nic.NetworkInterfaceType != NetworkInterfaceType.Loopback // ...ignore the loopback NIC as we don't want 127.0.0.1 (1 of 2)
&& nic.Name.IndexOf("loopback", StringComparison.OrdinalIgnoreCase) == -1 // ...ignore the loopback NIC as we don't want 127.0.0.1 (2 of 2)
&& nic.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) == -1 // ... ignore virtual NICs so that VMs don't conflict with IP resolution
)
.Select(n => n.GetIPProperties())
// All developer network connections should have the my-company-internal.com suffix
.Where(ipp => ipp.DnsSuffix.ToLowerInvariant().IndexOf("my-company-internal.com", StringComparison.OrdinalIgnoreCase) >= 0)
.Where(ipp => ipp.UnicastAddresses.Any(u => u.Address.AddressFamily == AddressFamily.InterNetwork))
// Is this order by correct?
.OrderByDescending(ipp => ipp.GetIPv4Properties().Index)
.SelectMany(ipp => ipp.UnicastAddresses.Where(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork))
.FirstOrDefault();
I know with the IPV4Properties.Index - it is only populated when IPv4 is enabled; I don't know if corresponds to priority or metric, and whether or not they are guaranteed to be distinct.

I had the same problem here a few weeks ago. I figured out that the NIC priority is persisted in Windows Registry, and there are a few PowerShell scripts that can give you the NIC order, but not the IP addresses. So, I've written the code below and it worked for me. You can use it to see additional info like dns suffix, gateway address and plus.
You just have to call RMSNetUtils.GetTopIpv4Ip(string.Empty)
public class RMSNetUtils
{
private static string _linkagePath = #"SYSTEM\CurrentControlSet\Services\Tcpip\Linkage";
private static string _interfacesPath = #"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\";
private static List<string> GetBindingsPriority()
{
using (var bindMasterKey = Registry.LocalMachine.OpenSubKey(_linkagePath))
{
var bind = (string[]) bindMasterKey.GetValue("Bind");
var deviceList = bind.Select(x => $#"{_interfacesPath}{x.Replace("\\Device\\", string.Empty)}")
.ToList();
var result = new List<string>();
foreach (var device in deviceList)
{
using (var bindKey = Registry.LocalMachine.OpenSubKey(device))
{
var fixIP = (string[])bindKey.GetValue("IPAddress");
if (fixIP != null)
{
result.Add( fixIP.FirstOrDefault());
continue;
}
var dhcpIp = bindKey.GetValue("DhcpIPAddress");
if (dhcpIp != null)
{
result.Add((string) dhcpIp);
}
}
}
return result;
}
}
private static List<NICInformation> GetFilteredBindings()
{
var bindings = GetBindingsPriority();
var nicsInfo = GetIpList(GetInterNetworkAdapters());
var result = new List<NICInformation>();
foreach (var bind in bindings)
{
var nicInfo = nicsInfo.FirstOrDefault(y => string.Compare(y.IPv4, bind) == 0);
if(nicInfo!= null)
result.Add(nicInfo);
}
return result;
}
private static IEnumerable<IPAddress> GetInterNetworkAdapters()
{
IPHostEntry local = Dns.GetHostEntry(string.Empty);
return (from ipa in local.AddressList
where ipa.AddressFamily == AddressFamily.InterNetwork
select ipa);
}
public static string GetFirstIpv4Ip()
{
return GetFirstIpv4Ip(String.Empty);
}
private static List<NICInformation> GetIpList(IEnumerable<IPAddress> ips)
{
var ipAddresses = ips.Select(x => x.ToString()).ToList();
var result = new List<NICInformation>();
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
var ipStr = ip.Address.ToString();
if (ipAddresses.Contains(ipStr))
{
var nic = new NICInformation();
nic.IPv4 = ip.Address.ToString();
nic.Mask = ip.IPv4Mask.ToString();
nic.DnsSuffix = ni.GetIPProperties().DnsSuffix;
var gateway = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if(gateway!=null)
nic.Gateway = gateway.Address.ToString();
result.Add(nic);
}
}
}
}
}
return result;
}
public static string GetTopIpv4Ip(string hostName)
{
if (!string.IsNullOrEmpty(hostName))
return GetFirstIpv4Ip(hostName);
var item = GetFilteredBindings().FirstOrDefault();
return item == null ? hostName : item.IPv4;
}
public static string GetFirstIpv4Ip(string hostName)
{
var ip = string.Empty;
try
{
IPHostEntry local = Dns.GetHostEntry(hostName);
var result = GetInterNetworkAdapters().FirstOrDefault();
return result != null ? result.ToString() : hostName;
}
catch (SocketException ex)
{
ip = hostName;
}
return ip;
}
}
public class NICInformation
{
public string DnsSuffix {get;set;}
public string IPv4 {get;set; }
public string Gateway {get;set;}
public string Mask {get;set;}
}

Related

Which addresses are for the network? [duplicate]

I have a VirtualBox VM installed on my machine and as such there is an ethernet adapter that appears for it. I'm enumerating through the list of my machine's IP address via the following:
public string GetLocalIpAddress()
{
try
{
string strHostName = Dns.GetHostName();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
foreach (IPAddress ip in ipEntry.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return string.Format("({0})", ip.ToString());
}
}
}
catch(Exception e)
{
Global.ApplicationLog.AddApplicationLog(EnumAppEventTypes.SYSTEM_ERROR, e.ToString());
}
return "";
}
My problem is that the virtual machine's ethernet adapter also catches on the condition:
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
Is there a way of picking out my machine's local ip address and disregarding my virtual machine's?
I'm refining Andrej Arh's answer, as the IP Address reported by GatewayAddresses can also be "0.0.0.0" instead of just null:
public static string GetPhysicalIPAdress()
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if (addr != null && !addr.Address.ToString().Equals("0.0.0.0"))
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
return ip.Address.ToString();
}
}
}
}
}
return String.Empty;
}
Use WMI and check ConnectorPresent property for physical device.
public static string GetPhysicalIPAdress()
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ConnectorPresent(ni))
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return ip.Address.ToString();
}
}
}
}
}
return string.Empty;
}
private static bool ConnectorPresent(NetworkInterface ni)
{
ManagementScope scope = new ManagementScope(#"\\localhost\root\StandardCimv2");
ObjectQuery query = new ObjectQuery(String.Format(
#"SELECT * FROM MSFT_NetAdapter WHERE ConnectorPresent = True AND DeviceID = '{0}'", ni.Id));
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection result = searcher.Get();
return result.Count > 0;
}
There is one option. VM IP don't have Default Gateway, so, exclude all IP's without Default Gateway.
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if (addr != null)
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(ni.Name);
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine(ip.Address.ToString());
}
}
}
}
}
You can disregard the Ethernet adapter by its name. As the VM Ethernet adapter is represented by a valid NIC driver, it is fully equivalent to the physical NIC of your machine from the OS's point of view.

Identify individual Azure app service machines (especially behind a load balancer)

I want to identify individual Azure app service machines so that I can record info in a database. I was thinking I would use the local ip address of the machine using the function below but I get an empty string returned back. The code works for VM's but not for app services. Any thoughts (especially if these are eventually behind a load balancer and running identical code. (any string is ok... it doesn't have to be an ip address)
public static string GetLocalIpAddress()
{
UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != OperationalStatus.Up)
continue;
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
continue;
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
if (IPAddress.IsLoopback(address.Address))
continue;
if (!address.IsDnsEligible)
{
if (mostSuitableIp == null)
mostSuitableIp = address;
continue;
}
// The best IP is the IP got from DHCP server
if (address.PrefixOrigin != PrefixOrigin.Dhcp)
{
if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
mostSuitableIp = address;
continue;
}
return address.Address.ToString();
}
}
return mostSuitableIp != null
? mostSuitableIp.Address.ToString()
: "";
}

Why does getting an IP address throw an exception?

Background:
My program starts up and it must obtain the IP address of the machine it is running on.
It is the "server" in a client-server architecture that receives incoming tcp-ip messages.
I should also add the machine :
Has multi-ip addresses available
Is running Windows 2008 R2 Server
Here is the code that obtains the IP address:
public bool IsNetworkAvailable
{
get
{
return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
}
}
public string thisIP { get; private set; }
public void GetThisIP()
{
if (!string.IsNullOrEmpty(thisIP))
{
return;
}
thisIP = "*";
if (IsNetworkAvailable)
{
using (System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(
System.Net.Sockets.AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Dgram, 0))
{
socket.Connect("11.0.1.5", 65530);
System.Net.IPEndPoint endPoint = socket.LocalEndPoint as System.Net.IPEndPoint;
thisIP = endPoint.Address.ToString();
}
}
}
Here is the error message:
(0x80004005): A socket operation was attempted to an unreachable network 11.0.1.5:65530
at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)
SOLUTION:
I have changed my code to what rodcesar.santos suggested in this:
Get local IP address
here is my (modified) code (and it works)
System.Net.NetworkInformation.UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)
{
continue;
}
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
{
continue;
}
if (mostSuitableIp != null)
{
break;
}
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
{
continue;
}
if (System.Net.IPAddress.IsLoopback(address.Address))
{
continue;
}
if (mostSuitableIp == null && address.IsDnsEligible)
{
mostSuitableIp = address;
break;
}
}
}
thisIP = mostSuitableIp != null ? mostSuitableIp.Address.ToString() : "";
After reading the accepted answer # A socket operation was attempted to an unreachable host,
I assume that the specific client-computer than receives this error has a somewhat faulty network.
Quoting #Stephen Cleary
This error indicates that the network was not connected or not configured correctly. It is definitely an error on the client machine, not your server.
There isn't much you can do to "solve" the problem. Pretty much all you can do is upgrade the client's network drivers and check for connection problems (maybe they're barely within wireless range, or the Ethernet cable is missing its locking tab).
System.Net.NetworkInformation.UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)
{
continue;
}
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
{
continue;
}
if (mostSuitableIp != null)
{
break;
}
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
{
continue;
}
if (System.Net.IPAddress.IsLoopback(address.Address))
{
continue;
}
if (mostSuitableIp == null && address.IsDnsEligible)
{
mostSuitableIp = address;
break;
}
}
}
thisIP = mostSuitableIp != null ? mostSuitableIp.Address.ToString() : "";

How to obtain Public IP of a device using C# with out using external API/Services

public static string GetPublicIp()
{
HttpContext context = HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
I'm trying to get the client Public IP but the above code only returns the client Local IP. If different people are connecting to my organisation from the same organisations network, i want to get only their public IP address. I'm not intrested in their local IPs, is this possible.
Below is one solution i have so far seen but i'm NOT liking it.
public static string GetPublicIp()
{
string direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org");
using (WebResponse response1 = request.GetResponse())
using (StreamReader stream1 = new StreamReader(response1.GetResponseStream()))
{
direction = stream1.ReadToEnd();
}
//Search for the ip in the html
int first1 = direction.IndexOf("Address: ") + 9;
int last1 = direction.LastIndexOf("</body>");
direction = direction.Substring(first1, last1 - first1);
return direction;
}
The above sample solution can get me the public IP but i don't want to be tied to an external service that i have no control over because if that service is down then iam screwed and the performance is terrible.
Does any one know how i can get the clients public IP with out calling external services?
This method gives you the local ip address. I've copied it from a WinRT-Solution, maybe the class names are a bit different in other .NET environments.
private static string GetLocalAddress()
{
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
//IanaInterfaceType == 71 => Wifi
//IanaInterfaceType == 6 => Ethernet (Emulator)
if (hn.IPInformation != null &&
(hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
|| hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
{
return hn.DisplayName;
}
}
return IpAddress.Broadcast.Address;
}
EDIT: The following method prints out all local ip addresses.
private static void PrintLocalAddresses()
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var ni in interfaces)
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
{
var adapterProperties = ni.GetIPProperties();
foreach (var x in adapterProperties.UnicastAddresses)
{
if (x.Address.AddressFamily == AddressFamily.InterNetwork)
{
Console.WriteLine(x.Address);
}
}
}
}
}

Reliable method to get machine's MAC address in C#

I need a way to get a machine's MAC address, regardless of the OS it is running, by using C#.
The application will need to work on XP/Vista/Win7 32bit and 64bit, as well as on those OSs but with a foreign language default. Also, many of the C# commands and OS queries don't work across all the OSs.
Do you have any ideas?
I have been scraping the output of ipconfig /all but this is terribly unreliable as the output format differs on every machine.
Cleaner solution
var macAddr =
(
from nic in NetworkInterface.GetAllNetworkInterfaces()
where nic.OperationalStatus == OperationalStatus.Up
select nic.GetPhysicalAddress().ToString()
).FirstOrDefault();
Or:
String firstMacAddress = NetworkInterface
.GetAllNetworkInterfaces()
.Where( nic => nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback )
.Select( nic => nic.GetPhysicalAddress().ToString() )
.FirstOrDefault();
Here's some C# code which returns the MAC address of the first operational network interface. Assuming the NetworkInterface assembly is implemented in the runtime (i.e. Mono) used on other operating systems then this would work on other operating systems.
New version: returns the NIC with the fastest speed that also has a valid MAC address.
/// <summary>
/// Finds the MAC address of the NIC with maximum speed.
/// </summary>
/// <returns>The MAC address.</returns>
private string GetMacAddress()
{
const int MIN_MAC_ADDR_LENGTH = 12;
string macAddress = string.Empty;
long maxSpeed = -1;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
log.Debug(
"Found MAC Address: " + nic.GetPhysicalAddress() +
" Type: " + nic.NetworkInterfaceType);
string tempMac = nic.GetPhysicalAddress().ToString();
if (nic.Speed > maxSpeed &&
!string.IsNullOrEmpty(tempMac) &&
tempMac.Length >= MIN_MAC_ADDR_LENGTH)
{
log.Debug("New Max Speed = " + nic.Speed + ", MAC: " + tempMac);
maxSpeed = nic.Speed;
macAddress = tempMac;
}
}
return macAddress;
}
Original Version: just returns the first one.
/// <summary>
/// Finds the MAC address of the first operation NIC found.
/// </summary>
/// <returns>The MAC address.</returns>
private string GetMacAddress()
{
string macAddresses = string.Empty;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}
The only thing I don't like about this approach is if you have like a Nortel Packet Miniport or some type of VPN connection it has the potential of being chosen. As far as I can tell, there is no way to distinguish an actual physical device's MAC from some type of virtual network interface.
IMHO returning first mac address isn't good idea, especially when virtual machines are hosted. Therefore i check send/received bytes sum and select most used connection, that is not perfect, but should be correct 9/10 times.
public string GetDefaultMacAddress()
{
Dictionary<string, long> macAddresses = new Dictionary<string, long>();
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
macAddresses[nic.GetPhysicalAddress().ToString()] = nic.GetIPStatistics().BytesSent + nic.GetIPStatistics().BytesReceived;
}
long maxValue = 0;
string mac = "";
foreach(KeyValuePair<string, long> pair in macAddresses)
{
if (pair.Value > maxValue)
{
mac = pair.Key;
maxValue = pair.Value;
}
}
return mac;
}
The MACAddress property of the Win32_NetworkAdapterConfiguration WMI class can provide you with an adapter's MAC address. (System.Management Namespace)
MACAddress
Data type: string
Access type: Read-only
Media Access Control (MAC) address of the network adapter. A MAC address is assigned by the manufacturer to uniquely identify the network adapter.
Example: "00:80:C7:8F:6C:96"
If you're not familiar with the WMI API (Windows Management Instrumentation), there's a good overview here for .NET apps.
WMI is available across all version of windows with the .Net runtime.
Here's a code example:
System.Management.ManagementClass mc = default(System.Management.ManagementClass);
ManagementObject mo = default(ManagementObject);
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (var mo in moc) {
if (mo.Item("IPEnabled") == true) {
Adapter.Items.Add("MAC " + mo.Item("MacAddress").ToString());
}
}
WMI is the best solution if the machine you are connecting to is a windows machine, but if you are looking at a linux, mac, or other type of network adapter, then you will need to use something else. Here are some options:
Use the DOS command nbtstat -a . Create a process, call this command, parse the output.
First Ping the IP to make sure your NIC caches the command in it's ARP table, then use the DOS command arp -a . Parse the output of the process like in option 1.
Use a dreaded unmanaged call to sendarp in the iphlpapi.dll
Heres a sample of item #3. This seems to be the best option if WMI isn't a viable solution:
using System.Runtime.InteropServices;
...
[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
...
private string GetMacUsingARP(string IPAddr)
{
IPAddress IP = IPAddress.Parse(IPAddr);
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
if (SendARP((int)IP.Address, 0, macAddr, ref macAddrLen) != 0)
throw new Exception("ARP command failed");
string[] str = new string[(int)macAddrLen];
for (int i = 0; i < macAddrLen; i++)
str[i] = macAddr[i].ToString("x2");
return string.Join(":", str);
}
To give credit where it is due, this is the basis for that code:
http://www.pinvoke.net/default.aspx/iphlpapi.sendarp#
We use WMI to get the mac address of the interface with the lowest metric, e.g. the interface windows will prefer to use, like this:
public static string GetMACAddress()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
string mac = (from o in objects orderby o["IPConnectionMetric"] select o["MACAddress"].ToString()).FirstOrDefault();
return mac;
}
Or in Silverlight (needs elevated trust):
public static string GetMACAddress()
{
string mac = null;
if ((Application.Current.IsRunningOutOfBrowser) && (Application.Current.HasElevatedPermissions) && (AutomationFactory.IsAvailable))
{
dynamic sWbemLocator = AutomationFactory.CreateObject("WbemScripting.SWBemLocator");
dynamic sWbemServices = sWbemLocator.ConnectServer(".");
sWbemServices.Security_.ImpersonationLevel = 3; //impersonate
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true";
dynamic results = sWbemServices.ExecQuery(query);
int mtu = int.MaxValue;
foreach (dynamic result in results)
{
if (result.IPConnectionMetric < mtu)
{
mtu = result.IPConnectionMetric;
mac = result.MACAddress;
}
}
}
return mac;
}
This method will determine the MAC address of the Network Interface used to connect to the specified url and port.
All the answers here are not capable of achieving this goal.
I wrote this answer years ago (in 2014). So I decided to give it a little "face lift". Please look at the updates section
/// <summary>
/// Get the MAC of the Netowrk Interface used to connect to the specified url.
/// </summary>
/// <param name="allowedURL">URL to connect to.</param>
/// <param name="port">The port to use. Default is 80.</param>
/// <returns></returns>
private static PhysicalAddress GetCurrentMAC(string allowedURL, int port = 80)
{
//create tcp client
var client = new TcpClient();
//start connection
client.Client.Connect(new IPEndPoint(Dns.GetHostAddresses(allowedURL)[0], port));
//wai while connection is established
while(!client.Connected)
{
Thread.Sleep(500);
}
//get the ip address from the connected endpoint
var ipAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
//if the ip is ipv4 mapped to ipv6 then convert to ipv4
if(ipAddress.IsIPv4MappedToIPv6)
ipAddress = ipAddress.MapToIPv4();
Debug.WriteLine(ipAddress);
//disconnect the client and free the socket
client.Client.Disconnect(false);
//this will dispose the client and close the connection if needed
client.Close();
var allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
//return early if no network interfaces found
if(!(allNetworkInterfaces?.Length > 0))
return null;
foreach(var networkInterface in allNetworkInterfaces)
{
//get the unicast address of the network interface
var unicastAddresses = networkInterface.GetIPProperties().UnicastAddresses;
//skip if no unicast address found
if(!(unicastAddresses?.Count > 0))
continue;
//compare the unicast addresses to see
//if any match the ip address used to connect over the network
for(var i = 0; i < unicastAddresses.Count; i++)
{
var unicastAddress = unicastAddresses[i];
//this is unlikely but if it is null just skip
if(unicastAddress.Address == null)
continue;
var ipAddressToCompare = unicastAddress.Address;
Debug.WriteLine(ipAddressToCompare);
//if the ip is ipv4 mapped to ipv6 then convert to ipv4
if(ipAddressToCompare.IsIPv4MappedToIPv6)
ipAddressToCompare = ipAddressToCompare.MapToIPv4();
Debug.WriteLine(ipAddressToCompare);
//skip if the ip does not match
if(!ipAddressToCompare.Equals(ipAddress))
continue;
//return the mac address if the ip matches
return networkInterface.GetPhysicalAddress();
}
}
//not found so return null
return null;
}
To call it you need to pass a URL to connect to like this:
var mac = GetCurrentMAC("www.google.com");
You can also specify a port number. If not specified default is 80.
UPDATES:
2020
Added comments to explain the code.
Corrected to be used with newer
operating systems that use IPV4 mapped to IPV6 ( like windows 10 ).
Reduced nesting.
Upgraded the code use "var".
public static PhysicalAddress GetMacAddress()
{
var myInterfaceAddress = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.OrderByDescending(n => n.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
.Select(n => n.GetPhysicalAddress())
.FirstOrDefault();
return myInterfaceAddress;
}
You could go for the NIC ID:
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {
if (nic.OperationalStatus == OperationalStatus.Up){
if (nic.Id == "yay!")
}
}
It's not the MAC address, but it is a unique identifier, if that's what you're looking for.
I really like AVee's solution with the lowest IP connection metric! But if a second nic with the same metric is installed, the MAC comparison could fail...
Better you store the description of the interface with the MAC. In later comparisons you can identify the right nic by this string. Here is a sample code:
public static string GetMacAndDescription()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
string mac = (from o in objects orderby o["IPConnectionMetric"] select o["MACAddress"].ToString()).FirstOrDefault();
string description = (from o in objects orderby o["IPConnectionMetric"] select o["Description"].ToString()).FirstOrDefault();
return mac + ";" + description;
}
public static string GetMacByDescription( string description)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
string mac = (from o in objects where o["Description"].ToString() == description select o["MACAddress"].ToString()).FirstOrDefault();
return mac;
}
let's say I have a TcpConnection using my local ip of 192.168.0.182. Then if I will like to know the mac address of that NIC I will call the meothod as: GetMacAddressUsedByIp("192.168.0.182")
public static string GetMacAddressUsedByIp(string ipAddress)
{
var ips = new List<string>();
string output;
try
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "ipconfig";
p.StartInfo.Arguments = "/all";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
catch
{
return null;
}
// pattern to get all connections
var pattern = #"(?xis)
(?<Header>
(\r|\n) [^\r]+ : \r\n\r\n
)
(?<content>
.+? (?= ( (\r\n\r\n)|($)) )
)";
List<Match> matches = new List<Match>();
foreach (Match m in Regex.Matches(output, pattern))
matches.Add(m);
var connection = matches.Select(m => new
{
containsIp = m.Value.Contains(ipAddress),
containsPhysicalAddress = Regex.Match(m.Value, #"(?ix)Physical \s Address").Success,
content = m.Value
}).Where(x => x.containsIp && x.containsPhysicalAddress)
.Select(m => Regex.Match(m.content, #"(?ix) Physical \s address [^:]+ : \s* (?<Mac>[^\s]+)").Groups["Mac"].Value).FirstOrDefault();
return connection;
}
Really hate to dig up this old post but I feel the question deserves another answer specific to windows 8-10.
Using NetworkInformation from the Windows.Networking.Connectivity namespace, you can get the Id of the network adapter windows is using. Then you can get the interface MAC Address from the previously mentioned GetAllNetworkInterfaces().
This will not work in Windows Store Apps as NetworkInterface in System.Net.NetworkInformation does not expose GetAllNetworkInterfaces.
string GetMacAddress()
{
var connectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (connectionProfile == null) return "";
var inUseId = connectionProfile.NetworkAdapter.NetworkAdapterId.ToString("B").ToUpperInvariant();
if(string.IsNullOrWhiteSpace(inUseId)) return "";
var mac = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => inUseId == n.Id)
.Select(n => n.GetPhysicalAddress().GetAddressBytes().Select(b=>b.ToString("X2")))
.Select(macBytes => string.Join(" ", macBytes))
.FirstOrDefault();
return mac;
}
string mac = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up && (!nic.Description.Contains("Virtual") && !nic.Description.Contains("Pseudo")))
{
if (nic.GetPhysicalAddress().ToString() != "")
{
mac = nic.GetPhysicalAddress().ToString();
}
}
}
MessageBox.Show(mac);
Changed blak3r his code a bit. In case you have two adapters with the same speed. Sort by MAC, so you always get the same value.
public string GetMacAddress()
{
const int MIN_MAC_ADDR_LENGTH = 12;
string macAddress = string.Empty;
Dictionary<string, long> macPlusSpeed = new Dictionary<string, long>();
try
{
foreach(NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
System.Diagnostics.Debug.WriteLine("Found MAC Address: " + nic.GetPhysicalAddress() + " Type: " + nic.NetworkInterfaceType);
string tempMac = nic.GetPhysicalAddress().ToString();
if(!string.IsNullOrEmpty(tempMac) && tempMac.Length >= MIN_MAC_ADDR_LENGTH)
macPlusSpeed.Add(tempMac, nic.Speed);
}
macAddress = macPlusSpeed.OrderByDescending(row => row.Value).ThenBy(row => row.Key).FirstOrDefault().Key;
}
catch{}
System.Diagnostics.Debug.WriteLine("Fastest MAC address: " + macAddress);
return macAddress;
}
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
PhysicalAddress Mac = nic.GetPhysicalAddress();
}
}
ipconfig.exe is implemented using various DLLs including iphlpapi.dll ... Googling for iphlpapi reveals a corresponding Win32 API documented in MSDN.
Try this:
/// <summary>
/// returns the first MAC address from where is executed
/// </summary>
/// <param name="flagUpOnly">if sets returns only the nic on Up status</param>
/// <returns></returns>
public static string[] getOperationalMacAddresses(Boolean flagUpOnly)
{
string[] macAddresses = new string[NetworkInterface.GetAllNetworkInterfaces().Count()];
int i = 0;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up || !flagUpOnly)
{
macAddresses[i] += ByteToHex(nic.GetPhysicalAddress().GetAddressBytes());
//break;
i++;
}
}
return macAddresses;
}

Categories