Shammer's Philosophy

My private adversaria

gethostbyaddr を試してみた。

localhost という文字列から、127.0.0.1 という結果を得るにはどうすればよいか、を調べていたが、
最初に見つけたのは、How to use gethostbyaddr() functionというサイト。gethostbyaddr という関数名からは、IP アドレスからホスト名を見つける関数のようだ。やりたいこととは逆だけれども、試しに動かしてみた。

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/time.h>

int main(int argc, char *args[]){
    struct hostent *hp;
    char *ip;
    in_addr_t data;

    if (argc == 2) {
	ip = args[1];
	data = inet_addr(ip);
	hp = gethostbyaddr(&data, 4, AF_INET);
	if (hp == NULL) {
	    printf("No such host.\n");
	}
	else {
	    printf("Success!\n");
	}
    }
    else {
	printf("Usage: %s $IP_ADDRESS\n", args[0]);
    }
    return 0;
}

実行結果は以下。

$ gcc reversedns.c
$ ./a.out localhost
Success!

実際のアドレスとかを取得するには、struct hostent の内容を知らないといけないようだ。ちなみに、gethostbyaddr は、netdb.h に定義されていると思われる。このインクルードを外すと以下のような Warning となった。

$ gcc reversedns.c
reversedns.c:15:7: warning: implicit declaration of function 'gethostbyaddr' is
      invalid in C99 [-Wimplicit-function-declaration]
        hp = gethostbyaddr(&data, 4, AF_INET);
             ^
reversedns.c:15:5: warning: incompatible integer to pointer conversion assigning
      to 'struct hostent *' from 'int' [-Wint-conversion]
        hp = gethostbyaddr(&data, 4, AF_INET);
           ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 warnings generated.
$