tags:

views:

2029

answers:

3

From C#, I want to do the equivalent of the following:

arp -a |findstr 192.168.1.254

Alternatively, the answer could call the SendARP function and get the results.

This will allow my application to do some other processing that requires the MAC address.

+6  A: 

SendARP P/Invoke goes like this:

[DllImport("iphlpapi.dll", ExactSpelling=true)]
public static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen );

PInvoke.NET has this example:

IPAddress dst = IPAddress.Parse("192.168.2.1"); // the destination IP address

byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
if (SendARP((int)dst.Address, 0, macAddr, ref macAddrLen) != 0)
     throw new InvalidOperationException("SendARP failed.");

string[] str = new string[(int)macAddrLen];
for (int i=0; i<macAddrLen; i++)
     str[i] = macAddr[i].ToString("x2");

Console.WriteLine(string.Join(":", str));
jop
Things to know about this answer that I discovered while testing on Windows XP using Wireshark:1) If the IP/MAC Address pair is already in the ARP cache, the ARP request packet will NOT be sent out on the network, but SendARP will still return the (potentially stale) macAddress it has in its cache. 2) This method is potentially very slow if using only a single thread. Looping through a full subnet of IP addresses (eg. 192.168.1.x) using a single thread took 250+ seconds (1 second per IP address.) Making it massively multi-threaded took less than a second for all 250+ addresses.
Pretzel
A: 

Hook into the WMI subsystem. Some VBScript code to get going in the right direction is here

boost
+1  A: 

To find your own:

Add a reference to System.Management

ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

ManagementObjectCollection mcCol = mc.GetInstances();

foreach (ManagementObject mcObj in mcCol)
{
  Console.WriteLine(mcObj["Caption"].ToString());
  Console.WriteLine(mcObj["MacAddress"].ToString());
}

Not sure about finding that of another device.

Douglas Anderson