How to get the IP address of the machine in C #

zhaozj2021-02-11  202

How to get the IP address of the machine to use the DNS class and get the IP address of the machine. This article is not a technical overview or a large discussion, and more like how to get an IP address or host name. In Win32 API programming, you can use the Network API, similar to the .NET platform. The only difference is that you have to find and understand what namespace (Namespace) and classes that need to complete this task. The Network API is stored in the System.Net namespace in the .NET platform. The DNS class in the System.NET namespace can be used to get the machine name and IP address. DNS class provides a simple domain name interpretation function. The DNS class provides support for processing Internet Domain Name (DNS) information. These returned information includes multiple IP addresses and host alias. The list of returned is a collection or an array of iPaddress objects. The following code shows how to get an IP address through a given host name. DNSUTILITY code NAMESPACE NKUTILITIES

{

Using system;

Using system.net;

Public Class DNSUTILILITY

{

Public static int main (String [] ARGS)

{

String strhostname = new string ("" ");

IF (args.length == 0)

{

// First get the host name of the local machine

Strhostname = DNS.GETOSTNAME ();

Console.writeline ("Local Machine's Host Name:" strHostname);

}

Else

{

Strhostname = args [0];

}

/ / Then get a list of IP addresses through the host name

IPHOSTENTRY IPENTRY = DNS.GETHOSTBYNAME (STRHOSTNAME);

Ipaddress [] addr = ipentry.addresslist;

For (int i = 0; i

{

Console.writeLine ("IP Address {0}: {1}", i, addr [i] .tostring ());

}

Return 0;

}

}

} The interpretation of the code If you want to get the host name of the local machine, you can call the gethostname method without the parameter. You can then use the return result as a parameter to call the gethostByname method to get the ipaddresses list, and then traverse the Addresses collection to get the host's IP address. Tip Confirm that in your code already contains the System.Net namespace, otherwise the compiler will not know how to find the DNS class. Similarly, when you use VisualStudio.net to create a project, confirm that your system already contains System.Net.dll. For more detailed information on the DNS class and System.net namespace, please refer to the .NET SDK online documentation.

转载请注明原文地址:https://www.9cbs.com/read-3870.html

New Post(0)