[Socket] 연습문제4

조아리 ㅣ 2024. 7. 10. 11:11

반응형

Q. 임의의 호스트의 모데인 이름을 인자로 받아서 호스트의 IP 주소를 출력하는 프로그램 get_hostent.c를 작성하되 gethostbyname() 함수를 이용하시오. /etc/hosts 파일에 아래와 같이 가장의 호스트 주소를 한 줄을 추가한 후 그 아래의 방법으로 get_hostent.c를 실행하여 이 호스트의 IP 주소가 어떻게 나타나는지를 확인해 보시오.

# /etc/hosts 파일
10.0.2.5     test.page.com.ke

# 호스트 주소 확인
$ ./get_hostent test.page.com.ke

 

가상의 호스트인 test.page.com.ke 대신에 실제로 존재하는 호스트 이름을 /etc/hosts 파일에 기록하되 IP 주소는 실제와 다르게 기록한 경우에는 결과가 어떻게 나타나는지 확인하시오.

 

1. get_hostent.c 코딩

//----------------------------------
// 파일명	: get_hostent.c
// 기 능	: socket() 시스템 콜을 호출하고, 생성된 소켓번호를 출력
// 컴파일	: gcc get_hostent.c -o get_hostent
// 사용법	: ./get_hostent Domain
//----------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>

int main(int main(int argc, char *argv[]){
    struct hostent *hp;
    struct in_addr in;
    int i;
    char buf[20];

    if(argc<2){
        printf("Usage: %x hostname\n", argv[0]);
        exit(1);
    }

    hp = gethostbyname(argv[1]);
    if(hp==NULL){
        printf("gethostbyname fail\n");
        exit(0);
    }

    printf("호스트 이름\t\t: %s\n", hp->h_name);
    printf("호스트 주소타입 번호\t: %d\n", hp->h_addrtype);
    printf("호스트 주소의 길이\t: %d바이트\n", hp->h_length);
    for(i=0; hp->h_addr_list[i];i++){
        memcpy(&in.s_addr, hp->h_addr_list[i],sizeof(in.s_addr));
        inet_ntop(AF_INET, &in, buf, sizeof(buf));
        printf("IP 주소(%d번째)\t\t: %s\n", i+1, buf);
    }
    for(i=0;hp->h_aliases[i];i++){
    	printf("호스트 별명(%d번째)\t: %s", i+1, hp->h_aliases[i]);
    }
    puts("");

    return 0;
}

 

 

2. 컴파일

gcc get_hostent.c -o get_hostent

 

 

3. test.page.com.ke 확인

실행
$ ./get_hostent test.page.com.ke

결과
호스트 이름                : test.page.com.ke
호스트 주소타입 번호 : 2
호스트 주소의 길이     : 4 Bytes
IP 주소(1번째)            : 10.0.2.5

 

 

4. 실제로 존재하는 도메인에 다른 IP 부여

10.0.2.6      google.com

 

 

5. get_hostent 확인

실행
$ ./get_hostent google.com

결과
호스트 이름                : google.com
호스트 주소타입 번호 : 2
호스트 주소의 길이     : 4 Bytes
IP 주소(1번째)            : 10.0.2.6

 

 

6. 4번 실행 안 했을 경우 결과

실행
$ ./get_hostent google.com

결과
호스트 이름                : google.com
호스트 주소타입 번호 : 2
호스트 주소의 길이     : 4 Bytes
IP 주소(1번째)            : 172.217.25.174

 

반응형