본문으로 바로가기
homeimage
  1. Home
  2. 컴퓨터/프로그래밍
  3. C언어 호스트 이름 구하기 함수 gethostname()

C언어 호스트 이름 구하기 함수 gethostname()

· 댓글개 · 바다야크

C gethostname() 호스트 이름 구하기 함수

호스트 이름을 구합니다.

  • 헤더: unistd.h
  • 형태: int gethostname(char *name, size_t len)
  • 인수: char *name 이름을 받을 문자열 버퍼
    size_t len 문자열 버퍼 크기
  • 반환: 0 == 호스트 이름 구하기 성공
    -1 == 실패, errno는적당한 값으로 설정된다.

C언어 gethostname() 함수 예제

#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)
{
    char            host_name[80];
    struct hostent *host_entry;
    int             ndx;
                 
    if ( 0 != gethostname( host_name, sizeof( host_name))){
        printf( "gethostname() 실행 실패\n");
        exit( 1);
    }                 
    printf( "%s\n", host_name);
    
    host_entry = gethostbyname( host_name);
    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언어 gethostname() 예제 실행 결과

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

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