gethostbyname Pro Test Available

Source: Internet
Author: User

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

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.