2015-05-06 72 views
-1

在c中使用gethostbyname()來檢索主機的真實IP地址的正確方法是什麼?另外爲什麼人們會說DHCP會將這種方法置於潛在的危險之中?使用gethostbyname()查找IP

+0

https://msdn.microsoft.com/en-us/library/windows/desktop/ms738524(v=vs.85).aspx – Abhineet

+0

的* *正確的做法是不要使用'的gethostbyname( )'。它已被棄用。改用'getaddrinfo()'。至於爲什麼*潛在*危險是因爲它依賴於DNS查找,並且DNS攻擊和錯誤的DNS配置可能會報告虛假信息。 –

回答

0

gethostbyname()函數通過使用DNS查找名稱來返回有關主機的信息。

函數的返回數據類型和參數如下所示:

struct hostent* gethostbyname(const char *name); 

一個例子爲從主機名中提取IP地址的列表(在這種情況下,「mail.google.com」)如下所示:

char host_name = "mail.google.com"; 
struct hostent *host_info = gethostbyname(host_name); 

if (host_info == NULL) 
{ 
    return(-1); 
} 

if (host_info->h_addrtype == AF_INET) 
{ 
    struct in_addr **address_list = (struct in_addr **)host_info->h_addr_list; 
    for(int i = 0; address_list[i] != NULL; i++) 
    { 
     // use *(address_list[i]) as needed... 
    } 
} 
else if (host_info->h_addrtype == AF_INET6) 
{ 
    struct in6_addr **address_list = (struct in6_addr **)host_info->h_addr_list; 
    for(int i = 0; address_list[i] != NULL; i++) 
    { 
     // use *(address_list[i]) as needed... 
    } 
}