Shammer's Philosophy

My private adversaria

gethostbyname sample

gethostbyname のサンプルだが、hostent 内容出力 - Shammerismの実装をちょっと変更するだけでできた。以下の様な感じ。

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

int main(int argc, char *args[]){
    if( argc == 2 ){
	char *hoststring = args[1];
	struct hostent *hp;
	hp = gethostbyname(hoststring);
	if( hp == NULL ){
	    printf("No IP associated with %s\n", hoststring);
	}
	else {
	    printf("=== %s Info ===\n", hoststring);
	    char **alias = hp->h_aliases;
	    for( ; *alias != NULL ; alias++ ){
		printf("alias of %s is %s\n", hoststring, *alias);
	    }
	    printf("addrtype of %s is %d\n", hoststring, hp->h_addrtype);
	    char **addrlist = hp->h_addr_list;
	    for( ; *addrlist != NULL ; addrlist++ ){
		printf("%s has IP, %s\n", hp->h_name, inet_ntoa(*((struct in_addr *)addrlist)));
	    }
	}
    }
    else {
	printf("Usage: %s $IP_ADDRESS\n", args[0]);
    }
    return 0;
}

実行例は以下。

$ gcc gethostbyname-c.c
$ ./a.out localhost
=== localhost Info ===
addrtype of localhost is 2
localhost has IP, XXX.XXX.XXX.XXX
$
$ ./a.out www.google.com
=== www.google.com Info ===
addrtype of www.google.com is 2
www.google.com has IP, XXX
www.google.com has IP, XXX
www.google.com has IP, XXX
www.google.com has IP, XXX
www.google.com has IP, XXX
$

エイリアスはでなかったけれどこんなもんか?あと、loopback の 127.0.0.1 は表示されないんだな。ほとんど同じような内容になることが予想されるけれど、gethostbyname2も試してみよう。