본문 바로가기

TCP/IP

gethostbyname() 함수

/* 도메인 네임 -> 32비트 IP주소 할 때, gethostbyname() 함수를 사용한 프로그램*/


#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>

int main(int argc, char *argv[])
{
  struct hostent *myhost;
  struct in_addr myinaddr;  //IP 주소를 저장할 구조체
  int i;

  if(argc < 2)
  {
    printf("How to Use : %s host_name(domain name)\n", argv[0]);
    exit(0);
  }
  
  /* hostent 구조체 구하기 */
  myhost = gethostbyname(argv[1]);
  if(myhost == 0)
  {
    printf("error at gethostbyname\n");
    exit(0);
  }

  printf("official host name : \t\t%s\n", myhost->h_name);  //호스트이름 출력

  i = 0;
  while(myhost->h_aliases[i] != NULL)
  {
    printf("aliases name : \t\t\t%s\n", myhost->h_aliases[i]);  //호스트별명 출력
    i++;
  }

  printf("host address type : \t\t%d\n", myhost->h_addrtype);    //호스트주소타입 출력
  printf("length of host address : \t%d\n", myhost->h_length);  //호스트주소길이 출력

  i = 0;
  while(myhost->h_addr_list[i] != NULL)
  {
    myinaddr.s_addr = *((u_long *)(myhost->h_addr_list[i]));
    printf("IP address : \t\t\t%s\n", inet_ntoa(myinaddr));  //호스트주소를 dotted-decimal형태로 출력
    i++;
  }
  return 0;
}

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

inet_addr()함수, (=inet_aton)  (0) 2011.07.01
호스트pc(리틀엔디안) <-> 네트워크(빅엔디안)  (0) 2011.07.01
inet_ntoa() 함수  (0) 2011.07.01
소켓의 생성과 해지  (0) 2011.06.29
네트워크 프로그래밍 실습  (0) 2011.06.28