1. Use C # To Call The doscommand to obtain the MAC address of the local Nic
System. Diagnostics. Process p = new System. Diagnostics. Process ();
P. StartInfo. CreateNoWindow = true;
P. StartInfo. UseShellExecute = false;
P. StartInfo. RedirectStandardOutput = true;
P. StartInfo. FileName = "ipconfig ";
P. StartInfo. Arguments = "/all ";
P. Start ();
P. WaitForExit ();
String s = p. StandardOutput. ReadToEnd ();
MessageBox. Show (s. Substring (s. IndexOf ("Physical Address ......:") + 36,17 ));
2. Using the API and ARP protocol, you can only obtain MAC addresses of computers in the same network segment.
# Region By ARP
[DllImport ("Iphlpapi. dll")]
Private static extern int SendARP (Int32 dest, Int32 host, ref Int64 mac, ref Int32 length );
[DllImport ("Ws2_32.dll")]
Private static extern Int32 inet_addr (string ip );
Public static string GetMacByARP (string clientIP)
{
String ip = clientIP;
Int32 ldest = inet_addr (ip );
Int64 macinfo = new Int64 ();
Int32 len = 6;
Try
{
SendARP (ldest, 0, ref macinfo, ref len );
}
Catch
{
Return "";
}
String originalMACAddress = Convert. ToString (macinfo, 16 );
If (originalMACAddress. Length <12)
{
OriginalMACAddress = originalMACAddress. PadLeft (12, '0 ');
}
String macAddress;
If (originalMACAddress! = "0000" & originalMACAddress. Length = 12)
{
String mac1, mac2, mac3, mac4, mac5, mac6;
Mac1 = originalMACAddress. Substring (10, 2 );
Mac2 = originalMACAddress. Substring (8, 2 );
Mac3 = originalMACAddress. Substring (6, 2 );
Mac4 = originalMACAddress. Substring (4, 2 );
Mac5 = originalMACAddress. Substring (2, 2 );
Mac6 = originalMACAddress. Substring (0, 2 );
MacAddress = mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6;
}
Else
{
MacAddress = "";
}
Return macAddress. ToUpper ();
}
Public static IPAddress [] GetLocalIP ()
{
String hostName = Dns. GetHostName ();
IPHostEntry ipEntry = Dns. GetHostByName (hostName );
Return ipEntry. AddressList;
}
# Endregion