728x90

도메인이름을 이용해 IP 주소 얻어오기

- gethostbyname 함수 : hostname을 전달하여 성공 시 hostent 구조체 변수의 주소값을 얻어옴

    -> hostent : 도메인에 대한 정보가 담겨있는 구조체

- IP는 도메인 이름에 비해 변동이 심하기 때문에 IP를 직접 이용하기 보단 도메인 이름을 통해 IP를 얻어오게 하는 것이 효율적임

#include <netdb.h>

struct hostent* gethostbyname(const char* hostname);

typedef struct hostent {
  char  *h_name;			// 공식 도메인 이름
  char  **h_aliases;		// 추가적인 별칭의 도메인 이름
  short h_addrtype;			// IP 타입
  short h_length;			// IP 정보의 크기(IPv4 : 4 / IPv6 : 16)
  char  **h_addr_list;		// IP의 주소 정보
} HOSTENT, *PHOSTENT, *LPHOSTENT;
int main(int argc, char *argv[])
{
    struct hostent *host = gethostbyname("www.naver.com");
    
    if(!host) {
        printf("gethost... error");
    }
    
    printf("Official name: %s \n", host->h_name);
    
    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");
    
    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]));
    } // inet_ntoa로 in_addr 구조체의 ip정보를 문자열로 반환
    return 0;
}

 

IP 주소를 이용해 도메인이름을 얻어오기

- gethostbyaddr함수 : ip주소를 전달하여 성공 시 hostent 구조체 변수의 주소값을 얻어옴

#include <netdb.h>

struct hostent* gethostbyaddr(const char* addr, socklen_t len, int family);
int main(int argc, char *argv[])
{
    
    struct sockaddr_in addr;
    
    memset(&addr, 0, sizeof(addr));
    addr.sin_addr.s_addr=inet_addr("223.130.195.200");
    
    struct hostent *host = gethostbyaddr((char*)&addr.sin_addr, 4, AF_INET);
    if(!host) {
        printf("gethost... error");
    }
    printf("Official name: %s \n", host->h_name);
    
    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");
    
    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;
}

 

728x90

+ Recent posts