ddingz 2021. 12. 28. 12:13

4 바이트(32비트)의 IP 주소를 편의에 따라 www.github.com과 같은 도메인 네임 또는 52.78.231.108과 같은 dotted decimal 방식으로 표현하여 사용한다.
dotted decimal 표현을 저장하기 위해서는 숫자 변수가 아니라 15개의 문자로 구성된 스트링 변수가 사용된다.
주의할 것은 IP 데이터그램을 네트워크로 실제로 전송할 때 IP 헤더에는 4 바이트의 (binary) IP 주소만 사용할 수 있다.
dotted decimal로 표현된 52.78.231.108을 32비트의 IP 주소로 변환하려면 inet_pton() 함수를 사용하고, IP 주소를 dotted decimal로 변환하려면 inet_ntop()를 사용한다.
ntop는 mumerical to presentation의 의미이다.

#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

dotted decimal로 표현된 주소(예: 52.78.231.108)를 명령문 인자로 입력하면 이것을 inet_pton()을 이용하여 4 바이트의 IP 주소(hexa로는 6CE74E34)로 바꾸어 화면에 출력하고, 이 IP 주소로부터 inet_ntop()를 호출하여 다시 dotted decimal 주소를 얻는 프로그램이다.

#include <stdio.h>
#include <stdlib.h>
#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; // 32비트 IP 주소 구조체
    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.s_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(0x%X) = %s\n", inaddr.s_addr, buf);

    return 0;
}

실행 결과