2012-05-01 49 views
0

在UNIX中的C程序中,可以使用gethostbyname()來獲取像「localhost」這樣的域的地址。如何將gethostbyname()的結果轉換爲點分十進制符號。Unix - 如何獲取域名的IP地址?

struct hostent* pHostInfo; 
long nHostAddress; 

/* get IP address from name */ 
pHostInfo=gethostbyname("localhost"); 

if(!pHostInfo){ 
    printf("Could not resolve host name\n"); 
    return 0; 
} 

/* copy address into long */ 
memset(&nHostAddress, 0, sizeof(nHostAddress)); 
memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length); 

nHostAddress包含以下內容:

16777243 

如何轉換的結果,這樣我可以得到的輸出爲:

127.0.0.1 
+2

http://stackoverflow.com/questions/1680365/integer-to-ip-address-c – birryree

+0

你只需要正確格式化;每個字節對應一個IP字段(例如,第一個字節是'127'等) –

回答

1

可以從struct in_addr直接轉換成使用的字符串inet_ntoa()

char *address = inet_ntoa(pHostInfo->h_addr); 

你已經得到的值(16777243)看起來不對,但是 - 出現到1.0.0.27!

+0

可能與他的計算機的序列號或某事有關。 –

+0

我可以理解1.0.0.127,但27是莫名其妙的。 – duskwuff

+0

它實際上是1.0.0.127,@duskwuff請再檢查一次。 – Jake

0

很容易只要編譯此代碼

#include<stdio.h> 
#include<netdb.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 
int main() 
{ 
    struct hostent *ghbn=gethostbyname("www.kamonesium.in");//change the domain name 
    printf("Host Name->%s\n", ghbn->h_name); 
    printf("IP ADDRESS->%s\n",inet_ntoa(*(struct in_addr *)ghbn->h_name)); 
}