본문 바로가기

Etc/TCP/IP

도메인 이름을 이용해서 ip주소 얻어내기

도메인 이름을 이용해서 ip주소 얻어내기

#include <netdb.h>
struct hostent *gethostbyname(const char *name);

struct hostent
{
    char *h_name;        // official name
    char **h_aliases;    // alias list
    int h_addrtype;        // host address type
    int h_length;        // length of address
    char **h_addr_list;    // list of addresses
}

h_name        : 공식 도메인 이름이 저장
h_aliases    : 별칭 지정
h_addrtype    : IPv4 인지 IPv6인지를 알려준다.
h_length    : 4, 16 둘중하나. ㅎㅎ ipv4인지 ipv6인지..
h_addr_list    : 도메인에 해당되는 ip주소를 알려준다.


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>

void error_handling(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정보를 얻기
    //
    host = gethostbyname(argv[1]);

    if(!host)
        error_handling("gethost... error");

    printf("officially name : %s \n\n", host->h_name);

    //
    // 별칭 모두 보여주고
    //
    puts("Aliases-------------");
    for(i=0; host->h_aliases[i]; i++)
    {
        puts(host->h_aliases[i]);
    }

    //
    // IP버전을 알려주고
    //
    printf("Address Type : %s\n", host->h_addrtype == AF_INET?"AF_INET":"AAF_INET6");
    puts("IP Address-------------");

    //
    // 등록된 IP도 알려주고
    //
    for(i=0; host->h_addr_list[i]; i++)
    {
        puts(inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
    }

    return 0;
}

void error_handling(char *message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

'Etc > TCP/IP' 카테고리의 다른 글

TIME WAIT STATUS  (0) 2013.09.25
ip 주소를 이용해서 도메인 이름 알아내기  (0) 2013.09.25
Half-close 의 필요성  (0) 2013.09.25
UDP 기반의 데이터 입,출력 함수  (0) 2013.09.25
UDP 기반의 데이터 입,출력 함수  (0) 2013.09.25