When establishing the socket link, the IP address is required, but only the domain name, gethostbyname is a function to convert the domain name to IP;
#include <netdb.h>struct hostent *gethostbyname (constchar *hostname);
Return: A non-null pointer if successful, NULL if an error occurs, and set H_errno
#include <stdio.h>
#include <sys/types.h>/* cannot be reduced without affecting compilation */
#include <arpa/inet.h>/* cannot be reduced without affecting compilation */
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
int main (int argc, char **argv)
{
Char *ptr, **pptr;
Char Str[inet_addrstrlen];
struct Hostent *hptr;
while (--ARGC > 0)
{
ptr = *++ARGV;
if ((hptr = gethostbyname (ptr)) = = = NULL)
{
printf ("GetHostByName error for Host:%s:%s\n", PTR, Hstrerror (H_errno));
Continue
}
printf ("Official hostname:%s\n", hptr->h_name);
for (pptr = hptr->h_aliases; *pptr! = NULL; pptr++)
printf ("\talias:%s\n", *pptr);
Switch (hptr->h_addrtype) {
Case AF_INET:
Pptr = hptr->h_addr_list;
for (; *pptr! = NULL; pptr++)
printf ("\taddress:%s\n", Inet_ntop (Hptr->h_addrtype, *pptr, str, sizeof (str)));
Break
Default
printf ("Unknown address type");
Break
}
}
return 0;
}
The results are as follows:
[Email protected] testcompile]#./main baidu.comofficial hostname:baidu.com address:180.149. 132.47 Address:220.181. 57.217 Address:111.13. 101.208 Address:123.125. 114.144
Of course, if you cannot connect to the Internet, you can also use: hostname query your host name, and then use./main hostname, or direct./main localhost will have results.
The domain name and hostname are equivalent, the above uses the domain name, uses the hostname is uses the host name.
gethostbyname Pro Test Available