C # obtain the MAC address of the IP address in the LAN

Source: Internet
Author: User

Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;

Using system. runtime. interopservices;
Using system. net;

Namespace macapp
{
Public partial class form1: Form
{
[Dllimport ("ws2_32.dll")]
Private Static extern int inet_addr (string CP );
[Dllimport ("iphlpapi. dll")]
Private Static extern int sendarp (int32 destip, int32 srcip, ref int64 pmacaddr, ref int32 phyaddrlen );
Public form1 ()
{
Initializecomponent ();
}

Private void button#click (Object sender, eventargs E)
{
Richtextbox1.text = getmacaddress (textbox1.text); // obtain the MAC address of the remote IP address (cross-network segment not supported)
}
Private string getmacaddress (string hostip) // obtain the MAC address of the remote IP address (cross-network segment not supported)
{
String MAC = "";
Try
{
Int32 ldest = inet_addr (hostip); // convert an IP address from the point format to an unsigned long integer
Int64 macinfo = new int64 ();
Int32 Len = 6;
Sendarp (ldest, 0, ref macinfo, ref Len );
String tmpmac = convert. tostring (macinfo, 16). padleft (12, '0'); // convert it to hexadecimal notation. Note that some do not have 12 digits.
MAC = tmpmac. substring (0, 2). toupper ();//
For (INT I = 2; I <tmpmac. length; I = I + 2)
{
MAC = tmpmac. substring (I, 2). toupper () + "-" + MAC;
}
}
Catch (exception Mye)
{
MAC = "Mac error obtaining remote host:" + Mye. message;
}
Return MAC;
}

Private void form1_load (Object sender, eventargs E)
{
If (DNS. gethostentry (DNS. gethostname (). Addresslist. length> 0)
{
Textbox1.text = DNS. gethostentry (DNS. gethostname (). Addresslist [0]. tostring (); // obtain the local IP Address
}
}
}
}

Related Article

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.