Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- Python
- java
- 코테
- java정리
- 빅데이터
- 자바
- 프로그램
- 자바독학
- 프로그래머스
- 프로그래밍
- 코딩테스트
- 모의 주식
- 개발
- 코스닥
- C++
- 자바정리
- 백준
- SNS
- Project
- 이웃한 칸
- 사물인터넷
- backend
- 코딩
- 코딩독학
- Reflex
- 주가예측
- 개인프로젝트
- 개발자
- 풀스택프레임워크
- frontend
Archives
- Today
- Total
Creative Code
Chapter8(호스트 정보 조회) 본문
※gethostbyname.c파일
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
void error_handling(char *message);
int main(int argc, char *argv[])
{
int i;
struct hostent *host;
// 명령행 인자 체크
if (argc != 2) {
printf("Usage : %s <addr>\n", argv[0]);
exit(1);
}
// 호스트 정보 조회
host = gethostbyname(argv[1]);
if (!host)
error_handling("gethost... error");
printf("Official name: %s\n", host->h_name);
// 별칭(alias) 목록 출력
for (i = 0; host->h_aliases[i]; i++)
printf("Aliases %d: %s\n", i + 1, host->h_aliases[i]);
// 주소 타입 출력 (IPv4 또는 IPv6)
printf("Address type: %s\n",
(host->h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6");
// IP 주소 목록 출력
for (i = 0; host->h_addr_list[i]; i++)
printf("IP addr %d: %s\n", i + 1,
inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
return 0;
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
※gethostbyaddr.c파일
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
void error_handling(char *message);
int main(int argc, char *argv[])
{
int i;
struct hostent *host;
struct sockaddr_in addr;
// 명령행 인자 체크
if (argc != 2) {
printf("Usage : %s <IP>\n", argv[0]);
exit(1);
}
// sockaddr_in 구조체 초기화 및 IP 주소 설정
memset(&addr, 0, sizeof(addr));
addr.sin_addr.s_addr = inet_addr(argv[1]);
// IP 주소를 이용하여 호스트 정보 조회
host = gethostbyaddr((char*)&addr.sin_addr, 4, AF_INET);
if (!host)
error_handling("gethost... error");
// 호스트 정보 출력
printf("Official name: %s\n", host->h_name);
// 호스트의 별칭(alias) 목록 출력
for (i = 0; host->h_aliases[i]; i++)
printf("Aliases %d: %s\n", i + 1, host->h_aliases[i]);
// 주소 타입 출력 (IPv4 또는 IPv6)
printf("Address type: %s\n",
(host->h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6");
// IP 주소 목록 출력
for (i = 0; host->h_addr_list[i]; i++)
printf("IP addr %d: %s\n", i + 1,
inet_ntoa(*(struct in_addr*)host->h_addr_list[i]);
return 0;
}
// 에러 핸들링 함수
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
'TCP IP 소켓프로그래밍' 카테고리의 다른 글
Chapter18(쓰레드,세마포어,mutex) (0) | 2023.10.11 |
---|---|
Chapter9(버퍼 입력받기) (0) | 2023.10.11 |
Chapter5(echo_client) (0) | 2023.10.11 |
Chapter4(서버에 순차접속) (0) | 2023.10.11 |
Chapter3(서버에 접속한 IP주소, 포트번호 출력) (0) | 2023.10.10 |