Get the network interface card (NIC) from a known MAC address (and get the IP addresses on that NIC)

/ Published in: C#
Save to your folder(s)

The code shows how to take a known MAC (e.g. "00:00:00:11:22:33") and locate the NIC which has that MAC. Note that the built-in MAC class for .NET is called PhysicalAddress (in System.Net.NetworkInformation). PhysicalAddress.Parse can take a string, so long as it has only numbers or numbers and dashes (-). We normally use colons (:) instead of dashes, so that's why I do a .Replace().

The last part of the code retrieves the IP Addresses associated with the selected NIC.

Copy this code and paste it in your HTML
  1. using System.Net.Sockets;
  2. using System.Net;
  3. using System.Net.NetworkInformation;
  5. string localNicMac = "00:00:00:11:22:33".Replace(":", "-"); // Parse doesn't like colons
  7. var mac = PhysicalAddress.Parse(localNicMac);
  8. var localNic =
  9. NetworkInterface.GetAllNetworkInterfaces()
  10. .Where(nic => nic.GetPhysicalAddress().Equals(mac)) // Must use .Equals, not ==
  11. .SingleOrDefault();
  12. if (localNic == null)
  13. {
  14. throw new ArgumentException("Local NIC with the specified MAC could not be found.");
  15. }
  17. var ips =
  18. localNic.GetIPProperties().UnicastAddresses
  19. .Select(x => x.Address);

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.