반응형
4 bytes (32 bits)의 IP주소를 편의에 따라 joari.tistory.com과 같은 도메인 네임 또는 19.92.8.29과 같은 dotted decimal(15개의 문자로 구성된 스트링 변수) 방식으로 표현하여 사용합니다.
소켓 프로그램에서는 이들 주소를 표현법을 상호변환할 수 있는 함수를 제공하고 있는데 세 가지 인터넷 주소 표현 방법과 이들을 상호변환 해주는 네 개의 주소변환 함수를 알아보겠습니다.
여기서 주의할 점은 IP 데이터그램을 네트워크로 실제로 전송할 때 IP 헤더에는 4 bytes(binary) IP 주소만 사용할 수 있다는 점입니다.
다음은 위 함수들의 사용 문법입니다.
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
const char *inet_ntop(int af, const void *src, char *dst, size_t cnt);
int inet_pton(int af, const char *src, void *dst);
사용 예제
//----------------------------------
// 파일명 : ascii_ip.c
// 기 능 : socket() 시스템 콜을 호쿨하고, 생성된 소켓번호를 출력
// 컴파일 : gcc ascii_ip.c -o ascii_ip
// 사용법 : ./ascii_ip
//----------------------------------
#include <stdio.h>
#include <stdlib.c>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char *argv[]) {
struct in_addr inaddr;
char buf[20];
if (argc < 2) {
printf("사용법 : %s IP 주소(dotted decimal)\n", argv[0]);
exit(0);
}
printf("* 입력한 dotted decimal IP주소 : %s\n, argv[1]);
inet_pton(AF_INET, argv[1], &inaddr.r_addr);
printf("inet_pton(%s) = 0x%X\n", argv[1],inaddr.s_addr);
inet_ntop(AF_INET, &inaddr,s_addr, buf, sizeof(buf));
printf("inet_ntop(ox%X) = %s\n", inaddr.s_addr, buf);
return 0;
}
실행 결과
$ ./ascii_ip 19.92.8.29
inet_pton (19.92.8.29) = 0x1D085C13
inet_ntop (0x1D085C13) = 19.92.8.29
솔라리스 시스템에서 inet_pton()이나 inet_ntop()를 사용하기 위해서는 아래와 같이 -lresolv 옵션이 필요합니다.
$ gcc ascii_ip.c -o accii_ip -lnsl -lsocket -lresolv
반응형