코딩/Network

[네트워크] DNS와 도메인, IP 주소 변환 함수

나야, 웅이 2023. 4. 15. 14:49
728x90
반응형
SMALL

도메인 이름

▶IP 주소처럼 호스트나 라우터의 고유한 식별자

▶IP 주소보다 기억하고 사용하기 쉬움

▶도메인 이름을 반드시 숫자 형태의 IP 주소로 변환해야 함

 

 

 

도메인 이름 ↔ IP 주소 변환 함수

도메인 이름 -> IP 주소 :gethostbyname

IP 주소 -> 도메인 이름 : gethostbyaddr

"192.108.0.3" -> char 형

 

 

 

hostent 구조체

 

 

 

1) hostent 구조체 IPv4를 사용하는 경우

2) hostent 구조체 IPv6를 사용하는 경우

 

도메인, IP 변환

사용자 정의 함수

 


DNS와 이름 변환 함수 실습

#include "../../Common.h"

#define TESTNAME "www.sch.ac.kr"

bool GetIPAddr(const char* name, struct in_addr* addr);
bool GetDomainName(struct in_addr addr, char* name, int namelen);


// 도메인 이름 -> IPv4 주소
bool GetIPAddr(const char* name, struct in_addr* addr)
{
	struct hostent* ptr = gethostbyname(name);
	if (ptr == NULL) {
		err_display("gethostbyname()");
		return false;
	}
	if (ptr->h_addrtype != AF_INET)
		return false;
	memcpy(addr, ptr->h_addr, ptr->h_length);
	return true;
}

// IPv4 주소 -> 도메인 이름
bool GetDomainName(struct in_addr addr, char* name, int namelen)
{
	struct hostent* ptr = gethostbyaddr((const char*)&addr,
		sizeof(addr), AF_INET);
	if (ptr == NULL) {
		err_display("gethostbyaddr()");
		return false;
	}
	if (ptr->h_addrtype != AF_INET)
		return false;
	strncpy(name, ptr->h_name, namelen);
	return true;
}

int main(int argc, char* argv[])
{
	// 윈속 초기화
	WSADATA wsa;
	if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
		return 1;

	printf("도메인 이름(변환 전) = %s\n", TESTNAME);

	// 도메인 이름 -> IP 주소
	struct in_addr addr;
	if (GetIPAddr(TESTNAME, &addr)) {
		// 성공이면 결과 출력
		char str[INET_ADDRSTRLEN];
		inet_ntop(AF_INET, &addr, str, sizeof(str));
		printf("IP 주소(변환 후) = %s\n", str);

		// IP 주소 -> 도메인 이름
		char name[256];
		if (GetDomainName(addr, name, sizeof(name))) {
			// 성공이면 결과 출력
			printf("도메인 이름(다시 변환 후) = %s\n", name);
		}
	}

	// 윈속 종료
	WSACleanup();
	return 0;
}
728x90
반응형
LIST