Recently, due to design requirements, the software needs to obtain the IP address of the machine and record it. Finally, I chose to use the DNS class and obtain the IP address of the machine.
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. BelowCodeShows how to obtain an IP address through the specified host name.
The Code is as follows:
Namespace dnstilities {using system; using system. net; public class DNS {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 Machine's 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.
Now you can record your IP address.