이 섹션에서는 로컬 시스템의 호스트 이름과 IP 주소를 보다 쉽게 보는 방법을 살펴보겠습니다. 호스트 이름과 IP를 찾는 C 프로그램을 작성합니다.
다음 기능 중 일부가 사용됩니다. 이러한 기능에는 다른 작업이 있습니다. 기능과 작업을 살펴보겠습니다.
| Sr.No | 기능 및 설명 |
|---|---|
| 1 | gethostname() 로컬 컴퓨터의 표준 호스트 이름을 찾습니다. |
| 2 | gethostbyname() 호스트 데이터베이스에서 호스트 이름에 해당하는 호스트 정보를 찾습니다. |
| 3 | iten_ntoa() IPv4 인터넷 네트워크 주소를 ASCII 문자열을 점분리 십진수 형식으로 변환합니다. |
예시
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void check_host_name(int hostname) { //This function returns host name for local computer
if (hostname == -1) {
perror("gethostname");
exit(1);
}
}
void check_host_entry(struct hostent * hostentry) { //find host info from host name
if (hostentry == NULL){
perror("gethostbyname");
exit(1);
}
}
void IP_formatter(char *IPbuffer) { //convert IP string to dotted decimal format
if (NULL == IPbuffer) {
perror("inet_ntoa");
exit(1);
}
}
main() {
char host[256];
char *IP;
struct hostent *host_entry;
int hostname;
hostname = gethostname(host, sizeof(host)); //find the host name
check_host_name(hostname);
host_entry = gethostbyname(host); //find host information
check_host_entry(host_entry);
IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0])); //Convert into IP string
printf("Current Host Name: %s\n", host);
printf("Host IP: %s\n", IP);
} 출력
Current Host Name: soumyadeep-VirtualBox Host IP: 127.0.1.1