< 08-2 : IP 주소와 도메인 이름 사이의 변환 예제 >
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
void error_handling(const char * message);
int main(int argc, char* argv[])
{
int i;
struct hostent *host;
if(argc != 2) {
printf("Usage : %s <addr> \n", argv[0]);
exit(1);
}
host = gethostbyname(argv[1]); // 메인 함수를 통해서 전달된 문자열을 인자로
// gethostbyname함수를 호출하고 있다.
if(!host)
error_handling("gethostbyname error");
printf("Official name: %s \n", host->h_name); // 공식 도메인 이름을 출력하고있다.
// 공식 도메인 이름 이외의 도메인 이름을 출력하고 있다.
// 반복문을 이렇게 구성한 이유는 그림 08-2를 통해 이해할 수 있다.
for(i =0; host->h_aliases[i]; i++)
printf("Aliases %d: %s \n", i+1, host->h_aliases[i]);
printf("Address type: %s \n",
(host->h_addrtype == AF_INET)?"AF_INET":"AF_INET6");
// IP 주소정보를 출력하고 있다. 그런데 이해할 수 없는 형변환을 진행하고 있다.
// 이와 관련해서는 잠시 후에 별도로 설명하겠다.
for(i =0; host->h_addr_list[i]; i++)
printf("IP addr %d: %s \n", i+ 1,
inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
return 0;
}
void error_handling(const char *message)
{
fputs(message, stderr);
fputc('\n',stderr);
exit(1);
}
-> 실행 결과는 아래와 같다.
github.com/HwangSaw/Ubuntu/blob/master/Ubuntu_TCP_IP/Chapter08/getHostByName.c