'programming'에 해당되는 글 387건

  1. 2015.03.16 gethostbyname

gethostbyname

programming/C_C++ 2015. 3. 16. 20:08
반응형

 

 

//
//  #include <netdb.h>
//
//  struct hostent  *gethostbyname(const char *);
//
//  struct  hostent {
//          char    *h_name;        /* official name of host */
//          char    **h_aliases;    /* alias list */
//          int     h_addrtype;     /* host address type */
//          int     h_length;       /* length of address */
//          char    **h_addr_list;  /* list of addresses from name server */
//  };
//  #define h_addr  h_addr_list[0]  /* address, for backward compatiblity */
//
//

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

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

 int i;

 if(argc != 2) {

  fprintf(stderr, "Usage : %s host_name(domain name)\n", argv[0]);  fflush(stderr);

  exit(0);

 }

 myHostEnt = gethostbyname(argv[1]);  /* hostent 구조체 구하기 */

 if(myHostEnt == NULL) {

  fprintf(stderr, "ERROR_FAIL gethostbyname\n");  fflush(stderr);

  exit(0);

 }

 fprintf(stdout, "official host name : %s\n", myHostEnt->h_name);  fflush(stdout);  /*공식적인호스트이름 출력*/

 i = 0;

 while(myHostEnt->h_aliases[i] != NULL) {

  fprintf(stdout, "alias list name : %s\n", myHostEnt->h_aliases[i]);  fflush(stdout);  /*호스트별명 출력*/

  i++;

 }

 fprintf(stdout, "host address type : %d\n", myHostEnt->h_addrtype);  fflush(stdout);    /*호스트주소타입 출력*/

    if( myHostEnt->h_addrtype == AF_INET ) {
  fprintf(stdout, "AF_INET\n");  fflush(stdout);
    }
    else if( myHostEnt->h_addrtype == AF_INET6 ) {
  fprintf(stdout, "AF_INET6\n");  fflush(stdout);
    }
    else {
  fprintf(stdout, "ETC.....\n");  fflush(stdout);
    }

 fprintf(stdout, "length of host address :%d\n", myHostEnt->h_length);  fflush(stdout);  /*호스트주소길이 출력*/

 i = 0;

 while(myHostEnt->h_addr_list[i] != NULL) {

  myInAddr.s_addr = *((u_long *)(myHostEnt->h_addr_list[i]));

  fprintf(stdout, "IP address : %s\n", inet_ntoa(myInAddr));  fflush(stdout);  /*호스트주소를 dotted-decimal형태로 출력*/

  i++;

 }

 return 0;

}

 

 

 

반응형
Posted by 공간사랑
,