How to obtain the IP address of a machine in C #

Source: Internet
Author: User
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.

Related Article

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.