How to obtain the IP and MAC addresses of local and remote hosts

Source: Internet
Author: User
Tags get ip static class

In this article, we are not prepared to discuss technical issues on a large scale. Just to tell you how we will get the IP address of a host. We can do this with the network API in the Win32 API, but in the. NET platform, what should we do? In fact, the operation method and API almost, but we have to understand namespace and class. The site of this aspect of the article a lot, about namespace and class content is not introduced.

. NET platform has a System.Net namespace, where the DNS class provides methods to obtain the server's service name or IP address. DNS is a static class, so it can create class instances directly. Gossip Less, we look at the specific procedures:

Namespace Nkutilities
{
Using System;
Using System.Net;

public class Dnsutility
{
public static int Main (string [] args)
{

String strhostname = new String ("");
if (args. Length = = 0)
{
Get the local IP address
The host name of the local machine was first obtained
Strhostname = DNS. GetHostName ();
Console.WriteLine ("Local Machine ' s Host Name:" + strhostname);
}
Else
{
Strhostname = Args[0];
}

Then use the host name to get the IP address list
A host may be more than one IP Oh, do not be misled by some people, hehe, think about the previous 163 and 169 will know
Iphostentry ipentry = DNS. gethostbyname (Strhostname);
IPAddress [] addr = ipentry.addresslist;

for (int i = 0; i < addr. Length; i++)
{
Console.WriteLine ("IP address {0}: {1}", I, addr[i]. ToString ());
}
return 0;
}
}
}
If you want to get the hostname, you can use the GetHostName method without parameters, and then use this host name as a parameter to the GetHostByName method to get the IPAddress list. Finally, the IP address in the output list.

How C # programming gets the IP and MAC addresses of local and remote hosts
Obtaining IP and MAC addresses using DNS classes and WMI specifications

In C # programming, it is easy to get the hostname and host IP address. It provides a DNS class that can easily get host names and IP addresses.

Example:
String strhostname = Dns.gethostname (); Get the host name of this machine
Iphostentry ipentry = Dns.gethostbyname (strhostname); Get native IP
String straddr = Ipentry.addresslist[0]. ToString (); Assuming the local host is a single NIC

In this code, two classes are used, one is the DNS class and the other is the Iphostentry class, both of which exist in the namespace System.Net.
The DNS class primarily retrieves information about a specific host from the Domain Name System (DNS), and the first line of code retrieves the local host name from the local DNS.
The Iphostentry class will associate a domain Name System or hostname with a set of IP addresses, which is used with the DNS class to get the IP address group of the host.
The way to get 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.
Here are two kinds of situation, one is the local MAC address, the other is the remote host MAC address. The acquisition is completely different.
When you obtain the MAC address of this computer, you can use the WMI specification to extract the MAC address from 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 a collection of management objects based on a specified query
The Managementobjectcollection class is a collection of managed objects, in the following example, which is assigned to the collection of managed objects by retrieving the object.

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 API function Sendarp. This function uses the ARP protocol to send ARP packets to the destination host, using the IP and MAC address pairs that are returned and 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

Try
{
Int64 macinfo = new Int64 ();
Int32 len = 6;
int res = Sendarp (ldest,0, ref macinfo, ref Len); Send ARP Package
Return convert.tostring (macinfo,16);
}
catch (Exception err)
{
Console.WriteLine ("Error:{0}", Err. message);
}
return 0.ToString ();

However, there is a big limitation when using this method to get Mac, which is to get the remote host MAC address of the same network segment only. Because under the standard network protocol, the ARP packet cannot transmit across the network segment, therefore wants to pass the ARP protocol is unable to inquire across the network segment device MAC address.

Sample programs:

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 length);
[DllImport ("Ws2_32.dll")]
private static extern Int32 inet_addr (string IP);

Get IP for this machine
public string Getlocalip ()
{
String strhostname = Dns.gethostname (); Get the host name of this machine
Iphostentry ipentry = Dns.gethostbyname (strhostname); Get native IP
String straddr = Ipentry.addresslist[0]. ToString ();
return (STRADDR);
}
Get Mac for this 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);
}

Get remote host IP
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 {
Straddr[i] = Ipaddr[i]. ToString ();
}
return (STRADDR);
}
Get remote host Mac
public string Getremotemac (string localip, String remoteip)
{
Int32 ldest= inet_addr (REMOTEIP); Destination IP
Int32 lhost= inet_addr (localip); Local IP

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 Network card information:");
Console.WriteLine (Gi.getlocalip () + "-" + Gi.getlocalmac ());

Console.WriteLine ("/N/R Remote network card information:");
string[] temp = GI.GETREMOTEIP ("Scmobile-tj2");
for (int i=0;i {
Console.WriteLine (Temp[i]);
}
Console.WriteLine (Gi.getremotemac ("192.168.0.3", "192.168.0.1"));
}
}

can be used. NET to obtain a host name or the IP address of a given host. To use a DNS class in your program, you need to include System.Net:
Include System.Net Reference
For example, to obtain http://www.mindcracker.com/IP address, the following code will complete this task:
Call DNS. GetHostName to get iphostentry and get the IP address list.
Iphostentry ipentry = DNS. gethostbyname ("www.mindcracker.com");
IPAddress [] ipaddr = ipentry.addresslist;
for (int i = 0; i < ipaddr.length; i++) {
Console.WriteLine ("IP address {0}: {1}", I, ipaddr[i]. ToString ());
}
In addition, GetHostName can return the host name of the local machine using a parameterless:
String strhostname = DNS. GetHostName ();
The host name is then passed as a parameter to gethostbyname to obtain the IP address information of the local machine.

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.