How to obtain the MAC of the Local Machine

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.