Friday, January 22, 2010

Finding MAC Address in C#

This code is used to find the MAC address on a given machine. There are two distinct ways. You can either use SNMP or another way. This is the other way. :)

using System.Net.NetworkInformation;

using System.IO;

using System.Runtime.InteropServices;

using System.Management;

using System.Net.Sockets;


public static System.Net.NetworkInformation.PhysicalAddress

GetMacFromIP(System.Net.IPAddress IP)

{

if (IP.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)

throw new ArgumentException("suppoerts just IPv4 addresses");

Int32 addrInt = IpToInt(IP);

Int32 srcAddrInt = IpToInt(IP);

byte[] mac = new byte[6]; // 48 bit

int length = mac.Length;

int reply = SendArp(addrInt, srcAddrInt, mac, ref length);

if (reply != 0)

throw new System.ComponentModel.Win32Exception(reply);

return new System.Net.NetworkInformation.PhysicalAddress(mac); ;

}

private static Int32 IpToInt(System.Net.IPAddress IP)

{

byte[] bytes = IP.GetAddressBytes();

return BitConverter.ToInt32(bytes, 0);

}

// of course in your code

void ShowMAC()

{

System.Net.IPAddress ip = System.Net.IPAddress.Parse(this.lblIP.Text);

this.lblMachine.Text = GetMacFromIP(ip).ToString();

}

No comments:

Post a Comment