(轉)gethostbyname() -- 用域名或主機名獲取IP地址


 

  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="www.baidu.com", **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);
    printf("addrtype:%d\n",hptr->h_addrtype);
    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)));

            printf("str is also : %s\n",str);
        break;
        default:
            printf("unknown address type\n");
        break;
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM