Return to Snippet

Revision: 23707
at February 11, 2010 13:48 by pckujawa


Initial Code
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;

string localNicMac = "00:00:00:11:22:33".Replace(":", "-"); // Parse doesn't like colons

var mac = PhysicalAddress.Parse(localNicMac);
var localNic =
    NetworkInterface.GetAllNetworkInterfaces()
        .Where(nic => nic.GetPhysicalAddress().Equals(mac)) // Must use .Equals, not ==
        .SingleOrDefault();
if (localNic == null)
{
    throw new ArgumentException("Local NIC with the specified MAC could not be found.");
}

var ips =
    localNic.GetIPProperties().UnicastAddresses
        .Select(x => x.Address);

Initial URL


Initial Description
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.

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

Initial Tags
mac, ip

Initial Language
C#