gethostbyname 亲测可用

建立Socket链接的时候需要IP地址,但是只有域名怎么办,gethostbyname就是一个将域名转换为IP的函数;

#include <netdb.h>

struct hostent *gethostbyname(const char *hostname);

返回:若成功则为非空指针,若出错则为NULL且设置h_errno


#include <stdio.h>
#include <sys/types.h> /*如果不影响编译也不能少*/
#include <arpa/inet.h> /*如果不影响编译也不能少*/
#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 ", ptr, hstrerror(h_errno));
continue;
}
printf("official hostname: %s ", hptr->h_name);


for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
printf(" alias:%s ", *pptr);


switch (hptr->h_addrtype) {
case AF_INET:
pptr = hptr->h_addr_list;
for ( ; *pptr != NULL; pptr++)
printf(" address:%s ", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
break;
default:
printf("unknown address type");
break;
}
}
return 0;
}

 

 结果如下:

[root@me testCompile]# ./main baidu.com
official hostname: baidu.com
    address:180.149.132.47
    address:220.181.57.217
    address:111.13.101.208
    address:123.125.114.144

 当然如果不能联网,也可以用:hostname 查询自己的主机名,然后用 ./main hostname,或者直接./main localhost一样会有结果。

域名和主机名是等效的,上面用的是域名,用hostname 就是用主机名。

原文地址:https://www.cnblogs.com/bugutian/p/4903093.html