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.