Use sendarp to obtain the MAC address

Source: Internet
Author: User

This document uses two methods to obtain the MAC address.

1.

Only Local.

Using system. Management;

 

Managementclass MC = new managementclass ("win32_networkadapterconfiguration"); managementobjectcollection moc2 = MC. getinstances (); foreach (managementobject Mo in moc2) {If (bool) Mo ["ipenabled"] = true) This. textbox1.text = Mo ["macaddress"]. tostring (); Mo. dispose ();

}

2. This method can obtain the remote MAC address.

Using system. runtime. interopservices;

[Dllimport ("iphlpapi. DLL ")] Static extern int sendarp (int32 destip, int32 srcip, ref int64 macaddr, ref int32 phyaddrlen); [dllimport (" ws2_32.dll ")] static extern int32 inet_addr (string ipaddr ); /// <summary> /// obtain the MAC address through sendarp /// </Summary> /// <Param name = "remoteip"> the IP address of the target machine, for example, 192.168.1.1) </param> // <returns> MAC address of the target machine </returns> Public static string getmacaddress (string remoteip) {stringbuilder macaddress = new stringbuilder (); try {int32 remote = inet_addr (remoteip); int64 macinfo = new int64 (); int32 length = 6; sendarp (remote, 0, ref macinfo, ref length ); string temp = convert. tostring (macinfo, 16 ). padleft (12, '0 '). toupper (); int x = 12; For (INT I = 0; I <6; I ++) {if (I = 5) {macaddress. append (temp. substring (X-2, 2);} else {macaddress. append (temp. substring (X-2, 2) + "-");} X-= 2;} return macaddress. tostring ();} catch {return macaddress. tostring ();}}

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.