#include <netdb.h>
struct hostent* gethostbyname(const char* hostname);
成功,返回非空指针,出错返回空指针,同时设置h_errno
hostent结构体定义如下:
struct hostent
{
char *h_name;// official name of host
char **h_aliases;//pointer to array of pointers to alias names
int h_addrtype;//host address type:AF_INET or AF_INET6
int h_lenght;//length of address 4 or 6
char **h_addr_list;//ptr to array of ptrs with IPv4 or IPv6 addrs
};
gethostbyname与我们介绍的其他套接口函数的不同之处在于,当发生错误时,它不设置errno,而是将全局整数h_errno设置为定义在头文件<netdb.h>中的下列常数中的一个:
1、HOST_NOT_FOUND
2、TRY_AGAIN
3、NO_RECOVERY
4、NO_DATA
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
#define INET6_ADDRESTRLEN 48
int main(int argc, char **argv)
{
char *ptr, **pptr;
char str[INET6_ADDRESTRLEN];
struct hostent* hptr;
while (--argc > 0) {
ptr = *++argv;
if ((hptr = gethostbyname(ptr)) == NULL) {
printf("gethostbyname error for host:%s:%s",
ptr, hstrerror(h_errno));
continue;
}
printf("official hostname:%s\n", hptr->h_name);
for (pptr = hptr->h_aliases; *pptr != NULL; pptr++) {
printf("\tallas:%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\n");
break;
}
}
}
return 0;
}