How to obtain an IP address through hostname in Network Programming

Source: Internet
Author: User

In network programming, most client requests from the server address are generally in the form of domain name + Access File.

For example: www.hehe.com/request.do

However, some companies use IP addresses as request addresses from testing to online.

Http://212.112.xxx, XX: 8080/request. Do

Both domain names and IP addresses have their respective advantages and disadvantages.

Because we all know that if the server is changed, if the IP address is used as the address, the client needs to be updated if the request address is written to the client.

Using a domain name is not a problem.

However, domain name convenience brings about performance or time sacrifice.

To put it bluntly, the domain name serves as an intermediary. When we initiate a request, the domain name is still resolved to an IP address for request.

Therefore, we can see that there is an additional step in the domain name resolution process.

So we can considerCodeDynamically change the request address domain name to an IP address.

Simply put, this takes into account the advantages of both.

The following code retrieves IP addresses based on the domain name:

// Obtain the IP address (nsstring *) getipwithhostname :( const nsstring *) hostname {const char * hostn = [hostname utf8string]; struct hostent * phot; @ try {phot = gethostbyname (hostn) ;}@ catch (nsexception * exception) {return nil;} struct in_addr ip_addr; memcpy (& ip_addr, phot-> h_addr_list [0], 4); char IP [20] = {0}; inet_ntop (af_inet, & ip_addr, IP, sizeof (IP); nsstring * stripaddress = [nsstring stringwithuf8string: IP]; return stripaddress ;}

Remember to add two header files to be included

# Include <netdb. h>
# Include <sys/socket. h>

The last note is that the hostname format does not contain http ://.

I used to carry this complete path and found that the obtained IP address is inconsistent with the IP address of our server.

You can just remove it.

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.