天天看點

gethostbyname() -- 用域名或主機名擷取IP位址

 #include <netdb.h>

    #include <sys/socket.h>

    struct hostent *gethostbyname(const char *name);

    這個函數的傳入值是域名或者主機名,例如"www.google.cn"等等。傳出值,是一個hostent的結構。如果函數調用失敗,将傳回null。

    struct hostent

    {

        char    *h_name;                

        char    **h_aliases; 

        int     h_addrtype;

        int     h_length;

        char    **h_addr_list; 

        #define h_addr h_addr_list[0] 

    }; 

    hostent->h_name

    表示的是主機的規範名。例如www.google.com的規範名其實是www.l.google.com。

    hostent->h_aliases

    表示的是主機的别名.www.google.com就是google他自己的别名。有的時候,有的主機可能有好幾個别名,這些,其實都是為了易于使用者記憶而為自己的網站多取的名字。

    hostent->h_addrtype     

    表示的是主機ip位址的類型,到底是ipv4(af_inet),還是pv6(af_inet6)

    hostent->h_length       

    表示的是主機ip位址的長度

    hostent->h_addr_lisst 

    表示的是主機的ip位址,注意,這個是以網絡位元組序存儲的。千萬不要直接用printf帶%s參數來打這個東西,會有問題的哇。是以到真正需要列印出這個ip的話,需要調用inet_ntop()。

    const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :

    這個函數,是将類型為af的網絡位址結構src,轉換成主機序的字元串形式,存放在長度為cnt的字元串中。傳回指向dst的一個指針。如果函數調用錯誤,傳回值是null。

#include <netdb.h>

#include <sys/socket.h>

#include <stdio.h>

int main(int argc, char **argv)

{

    char   *ptr, **pptr;

    struct hostent *hptr;

    char   str[32];

    ptr = argv[1];

    if((hptr = gethostbyname(ptr)) == null)

        printf(" gethostbyname error for host:%s\n", ptr);

        return 0; 

    }

    printf("official hostname:%s\n",hptr->h_name);

    for(pptr = hptr->h_aliases; *pptr != null; pptr++)

        printf(" alias:%s\n",*pptr);

    switch(hptr->h_addrtype)

        case af_inet:

        case af_inet6:

            pptr=hptr->h_addr_list;

            for(; *pptr!=null; pptr++)

                printf(" address:%s\n", 

                       inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));

            printf(" first address: %s\n", 

                       inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str)));

        break;

        default:

            printf("unknown address type\n");

    return 0;

}

編譯運作

-----------------------------

# gcc test.c

# ./a.out www.baidu.com

official hostname:www.a.shifen.com

alias:www.baidu.com

address:121.14.88.11

address:121.14.89.11

first address: 121.14.88.11