3. How do I know the IP address of a specific computer?
The. NET base class library has a static Dns class, which can be used to complete this task (Figure 2 ):
Figure 2
Dns provides a bunch of static methods to query common IP addresses.
For example, run the following code to obtain the local host name:
String LocalhostName = Dns. GetHostName ();
Run the following code to obtain the IP address of a Microsoft Host:
IPAddress [] ips = Dns. GetHostAddresses ("www.microsoft.com ");
By combining the above two sentences, we can get all the IP addresses of the local host:
IPAddress [] ips = Dns. GetHostAddresses (Dns. GetHostName ());
To obtain more detailed information, use the following Dns methods:
Public static IPHostEntry GetHostEntry (string hostNameOrAddress)
In the above Code, IPHostEntry is. the other class in the NET base class library (Figure 3) shows that it not only obtains all IPv4 and IPv6 addresses of the specified host, but also knows its host name (HostName) and alias (Aliases ).
Figure 3
The following figure shows the host information obtained by using GetHostEntry to directly access the Microsoft Website:
Host Name: lb2.www.ms.akadns.net
The host www.microsoft.com has the following IP addresses:
AddressFamily: InterNetwork Address: 207.46.170.10
AddressFamily: InterNetwork Address: 65.55.21.250
AddressFamily: InterNetwork Address: 207.46.170.123
AddressFamily: InterNetwork Address: 65.55.12.249
Note:
Some methods in the Dns class are discarded (Obsolete). When using it, pay attention to the warning information provided by the compiler.
For convenience, we encapsulate the function of obtaining the IPv4 address of the local host into a static method and put it into an AddressHelper static class:
Public static class AddressHelper
{
Public static IPAddress [] GetLocalhostIPv4Addresses ()
{
String LocalhostName = Dns. GetHostName ();
IPHostEntry host = Dns. GetHostEntry (LocalhostName );
List <IPAddress> addresses = new List <IPAddress> ();
Foreach (IPAddress ip in host. AddressList)
{
If (ip. AddressFamily = AddressFamily. InterNetwork)
Addresses. Add (ip );
}
Return addresses. ToArray ();
}
//......
}
Then add the above class to a MyNetworkLibrary class library, which will be used to encapsulate some common functions and will be used directly in subsequent articles.