HTTP Client の動作フロー その2 : gethostbyname() の実例

gethostbyname()を使用したサンプルコードをつくってみた。

/* gethostbyname.c */
#include <stdio.h>
#include <netdb.h>

int main (int argc, char *argv[]) {
	
	//変数宣言
	char *hostname;
	struct hostent *hostent;
	int i,j;
	char *err_mess = "";

	//引数が空の場合は終了
	if (argc == 1) {
		return 1;
	}

	//引数で渡されたホスト名を名前解決
	hostname = argv[1];
	hostent = gethostbyname(hostname);

	//エラー処理
	if (hostent == NULL) {

		switch (h_errno) {
			case HOST_NOT_FOUND:
				err_mess = "host not found";
				break;
			case NO_ADDRESS:
                                err_mess = "no address";
                                break;
			case NO_RECOVERY:
                                err_mess = "no recovery";
                                break;
			case TRY_AGAIN:
				err_mess = "try again";
				break;
			default:
				err_mess = "unknown error";
		}
		printf("error %d: %s\n", h_errno, err_mess);
		return 1;

	}

	//正常に名前解決できた場合は内容を表示
	printf("h_name : %s\n", hostent->h_name);

	printf("h_aliases :\n");
	for (i = 0; hostent->h_aliases[i] != NULL; i++) {
		printf("\t%s\n", hostent->h_aliases[i]);
	}  

	printf("h_addrtype : %d\n", hostent->h_addrtype);
	printf("h_length : %d\n", hostent->h_length);

	printf("h_addr_list :\n");
	for (i = 0; hostent->h_addr_list[i] != NULL; i++) {
		printf("\t");

		
		//IPアドレスを表示
		//TODO inet_ntop()か、ntohl()を使用する形式で書き換える
		for (j = 0; j < hostent->h_length; j++) {
                	//リトルエンディアンのアーキテクチャの場合不具合が起きる?
                	printf("%d", (unsigned char) hostent->h_addr_list[i][j]); 
			if( j < hostent->h_length-1 ) {
				printf(".");	
			}
		}
		printf("\n");
        }

	return 0;

}

こんな感じに使います。

$ ./gethostbyname localhost
h_name : localhost.localdomain
h_aliases :
	localhost
	ip6-localhost
	ip6-loopback
	localhost
h_addrtype : 2
h_length : 4
h_addr_list :
	127.0.0.1
	127.0.0.1
$ ./gethostbyname google.com
h_name : google.com
h_aliases :
h_addrtype : 2
h_length : 4
h_addr_list :
	74.125.153.147
	74.125.153.99
	74.125.153.103
	74.125.153.104
	74.125.153.105
	74.125.153.106