zoukankan      html  css  js  c++  java
  • 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 就是用主机名。

  • 相关阅读:
    数据结构最小生成树两个算法
    hdu-1742Ellipse(自适应辛普森)
    hdu1251统计难题
    codeforces-551C GukiZ hates Boxes
    CodeForces
    codeforces-894C Marco and GCD Sequence
    codeforces-892B Wrath
    codeforces-894B Ralph And His Magic Field
    CodeForces
    CodeForces
  • 原文地址:https://www.cnblogs.com/bugutian/p/4903093.html
Copyright © 2011-2022 走看看