C # to get the local IP address

Source: Internet
Author: User

Recently assisted a project to solve the problem of acquiring an IP address, the mobile client communicates with WebService, and then webservice the instruction to another PC via TCP communication. In the process of testing, there will always be WebService server and PC communication failure problem, but the use of TCP Debugging Tools for communication debugging the two machines can communicate, after debugging, for another network environment and can not communicate. Finally got the code, the troubleshooting is the IP address acquisition problem.

The original code gets the IP address by dns.gethostaddresses (Dns.gethostname ()) to get an array of IP addresses, and then gets the IP address in the array:

The original written code gets the third value in the array, in which write dead, in the test environment has been tested, but changed the customer environment communication and failure, helpless with Fildder for troubleshooting, the address of the communication problem, on the IP address to obtain errors, through the Internet to find information, to obtain an IP address replaced by:

1  Public Static IPAddress Localip = dns.gethostaddresses (dns.gethostname ())2       . Where (ip = = IP. AddressFamily = = System.Net.Sockets.AddressFamily.InterNetwork)3       . First ();

Dns.gethostaddresses (Dns.gethostname ()) to obtain an IP address of IPV4, IPV6, multiple network cards (including virtual network card) address, network environment, the data obtained is different, resulting in the acquisition of native IP address error.

filtering on IP addresses

1 dns.gethostaddresses (MachineName) 2      . Where (ip = = IP. AddressFamily = = System.Net.Sockets.AddressFamily.InterNetwork)3      . First ()

is to filter IP v4.

1 dns.gethostaddresses (MachineName) 2      . Where (ip = = IP. AddressFamily = = System.Net.Sockets.AddressFamily.InterNetworkV6)3      . First ()

is the IP address that filters the V6.

C # to get the local 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.