2012-05-01 17 views
0

UNIXのCプログラムでは、gethostbyname()を使用して "localhost"のようなドメインのアドレスを取得できます。どのようにgethostbyname()の結果をドット付き10進表記に変換しますか?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

これを正しくフォーマットするだけで済みます。各バイトは1つのIPフィールドに対応している(例えば、第1バイトは「127」など) –

答えて

1

あなたがAに直接struct in_addrから変換することができます文字列を使用してinet_ntoa()

あなたが持っている価値(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)); 
} 
関連する問題