본문으로 바로가기
homeimage
  1. Home
  2. 컴퓨터/프로그래밍
  3. C언어 도메인 이름으로 hostent 정보 구하기 함수 gethostbyname()

C언어 도메인 이름으로 hostent 정보 구하기 함수 gethostbyname()

· 댓글개 · 바다야크

C gethostbyname() 도메인 이름으로 hostent 정보 구하기 함수

주어진 호스트 name 에 상응하는 hostent 타입의 구조체를 반환한다.

  • 헤더: netdb.h
  • 형태: struct hostent *gethostbyname(const char *name)
  • 인수: const char *name 호스트 이름이거나 표준 점 표기법의 IPv4 주소, 콜론(그리고 점 표기법도 가능)표기법의 IPv6
  • 반환: NULL == 실패(h_errno 변수에 에러 넘버 대입), 성공 시 hostent 구조체 포인터

hostent 구조

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 compatibility.  */
};

C언어 gethostbyname() 함수 예제

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

int   main( void)
{
    struct hostent *host_entry;
    int             ndx;

    host_entry = gethostbyname( "badayak.com");

    if ( !host_entry){
        printf( "gethostbyname() 실행 실패\n");
        exit( 1);
    }
    for ( ndx = 0; NULL != host_entry->h_addr_list[ndx]; ndx++)
        printf( "%s\n", inet_ntoa( *(struct in_addr*)host_entry->h_addr_list[ndx]));

    return 0;
}

C언어 gethostbyname() 예제 실행 결과

]$ ./a.out
27.0.236.139
]$
SNS 공유하기
💬 댓글 개
최근글
이모티콘창 닫기
울음
안녕
감사해요
당황
피폐

이모티콘을 클릭하면 댓글창에 입력됩니다.