How do I obtain the IP address in C?

Source: Internet
Author: User
Obtain IP and MAC addresses using DNS and WMI specifications

In C # programming, it is easy to obtain the Host Name and Host IP address. It provides a DNS class that allows you to easily obtain the Host Name and IP address.

Example:
String strhostname = DNS. gethostname (); // obtain the Host Name of the local machine.
Iphostentry ipentry = DNS. gethostbyname (strhostname); // obtain the local IP address.
String straddr = ipentry. Addresslist [0]. tostring (); // assume that the local host is a single Nic.

Two classes are used in this Code. One is the DNS class and the other is the iphostentry class, both of which exist in the namespace system. net.
The DNS class mainly retrieves information about a specific host from the Domain Name System (DNS). The first line of the above Code retrieves the local host name from the local DNS.
The iphostentry class associates a Domain Name System or host name with a group of IP addresses. It is used with the DNS class to obtain the IP address group of the host.
The method for obtaining the IP address of a remote host is similar.

After obtaining the IP address, if you still need to obtain the MAC address of the NIC, You need to further explore.
There are two cases: the MAC address of the local host and the MAC address of the remote host.
When obtaining the MAC address of the local machine, you can use the WMI specification to extract the MAC address using the SELECT statement. In the. NET Framework, the implementation of the WMI specification is defined in the system. Management namespace.
The managementobjectsearcher class is used to retrieve and manage the collection of objects based on the specified query.
The managementobjectcollection class is a collection of management objects. In the following example, the collection of management objects returned by the retrieval object is assigned to it.

Example:
Managementobjectsearcher query = new managementobjectsearcher ("select * From win32_networkadapterconfiguration ");
Managementobjectcollection querycollection = query. Get ();
Foreach (managementobject Mo in querycollection)
{
If (Mo ["ipenabled"]. tostring () = "true ")
MAC = Mo ["macaddress"]. tostring ();
}

When obtaining the MAC address of a remote host, you need to borrow the API function sendarp. this function uses the ARP Protocol to send ARP packets to the target host, and uses the returned IP and MAC address pairs stored in the cache to obtain the MAC address of the remote host.

Example:
Int32 ldest = inet_addr (remoteip); // Destination IP
Int32 lhost = inet_addr (localip); // local IP Address

Try
{
Int64 macinfo = new int64 ();
Int32 Len = 6;
Int res = sendarp (ldest, 0, ref macinfo, ref Len); // send an ARP packet
Return convert. tostring (macinfo, 16 );
}
Catch (exception ERR)
{
Console. writeline ("error: {0}", Err. Message );
}
Return 0. tostring ();

However, using this method to obtain a MAC address is quite limited, that is, you can only obtain the MAC address of a remote host in the same network segment. in the standard network protocol, ARP packets cannot be transmitted across CIDR blocks. Therefore, you cannot query the MAC addresses of devices across CIDR blocks through arp.

Example program:

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

Public class getip
{
[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 );

// Obtain the IP address of the Local Machine
Public String getlocalip ()
{
String strhostname = DNS. gethostname (); // obtain the Host Name of the local machine.
Iphostentry ipentry = DNS. gethostbyname (strhostname); // obtain the local IP address.
String straddr = ipentry. Addresslist [0]. tostring ();
Return (straddr );
}
// Obtain the MAC of the Local Machine
Public String getlocalmac ()
{
String MAC = NULL;
Managementobjectsearcher query = new managementobjectsearcher ("select * From win32_networkadapterconfiguration ");
Managementobjectcollection querycollection = query. Get ();
Foreach (managementobject Mo in querycollection)
{
If (Mo ["ipenabled"]. tostring () = "true ")
MAC = Mo ["macaddress"]. tostring ();
}
Return (MAC );
}

// Obtain the remote host IP Address
Public String [] getremoteip (string remotehostname)
{
Iphostentry ipentry = DNS. gethostbyname (remotehostname );
IPaddress [] ipaddr = ipentry. Addresslist;
String [] straddr = new string [ipaddr. Length];
For (INT I = 0; I <ipaddr. length; I ++)
{
Straddr [I] = ipaddr [I]. tostring ();
}
Return (straddr );
}
// Obtain the MAC address of the remote host
Public String getremotemac (string localip, string remoteip)
{
Int32 ldest = inet_addr (remoteip); // Destination IP
Int32 lhost = inet_addr (localip); // local IP Address

Try
{
Int64 macinfo = new int64 ();
Int32 Len = 6;
Int res = sendarp (ldest, 0, ref macinfo, ref Len );
Return convert. tostring (macinfo, 16 );
}
Catch (exception ERR)
{
Console. writeline ("error: {0}", Err. Message );
}
Return 0. tostring ();
}


Public static void main (string [] ARGs)
{
Getip gi = new getip ();
Console. writeline ("Local Nic information :");
Console. writeline (GI. getlocalip () + "-" + GI. getlocalmac ());

Console. writeline ("/n/R remote Nic information :");
String [] temp = gi. getremoteip ("scmobile-tj2 ");
For (INT I = 0; I <temp. length; I ++)
{
Console. writeline (temp [I]);
}
Console. writeline (GI. getremotemac ("192.168.0.3", "192.168.0.1 "));
}
}

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.