Tips on how to use the DNS class and get the IP address of the machine
Introduction
This article is not a technical overview or a large-scale discussion, but more like a collection of tips on how to get an IP address or host name. You can use the NetWork API in Win32 API programming, which is similar to that on the. NET platform. The only difference is that you need to find and understand the namespace and class required to complete this task. On the. NET platform, the NetWork API exists in the System. Net namespace. The DNS class in the System. Net namespace can be used to obtain the machine name and IP address. The DNS class provides simple domain name interpretation functions. The DNS class provides support for processing Internet domain name (DNS) information. The returned information includes multiple IP addresses and host aliases. The returned list is a collection or an array of IPAddress objects. The following code shows how to obtain an IP address through the specified host name.
DNSUtility code
Namespace NKUtilities {using System; using System. net; public class DNSUtility {public static int Main (string [] args) {String strHostName = new String (""); if (args. length = 0) {// first obtain the host name strHostName = DNS of the local machine. getHostName (); Console. writeLine ("Local Machines Host Name:" + strHostName);} else {strHostName = args [0];} // obtain the IP address list IPHostEntry ipEntry = DNS by Host Name. 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 ;}}}
Code explanation
If you want to get the host name of the local machine, you can call the GetHostName method without adding a parameter. Then, you can call the GetHostByName method as a parameter to obtain the IPAddresses list and traverse the addresses collection to obtain the Host IP address.
Prompt
Make sure that your code contains the System. Net namespace. Otherwise, the compiler will not know how to find the DNS class. Similarly, when you create a project using Visual Studio. NET, make sure that your System already contains System. NET. Dll. For more information about the DNS class and System. Net namespace, see the. net sdk online documentation.