kyuseo의 게임 프로그래밍

윈속(WinSock) 함수 gethostbyname gethostname gethostbyaddr, inet_ntoa 사용법 및 주의사항 본문

C++ 개발

윈속(WinSock) 함수 gethostbyname gethostname gethostbyaddr, inet_ntoa 사용법 및 주의사항

kyuseo 2009. 6. 1. 14:47

개요..

 

윈도우 소켓 (WinSock) 함수인 주소를 IP어드레스로 변환할 수 있는 gethostbyname gethostname gethostbyaddr 함수의 사용 예 및 주의사항을 설명해드립니다.

 

gethostbyname 함수는 "www.tk.co.kr" 와 같은 영문 이름을 "211.41.11.xxx"와 같은 컴퓨터가 이해할 수 있는 숫자 기반의 주소로 변환하는 함수입니다. 하지만 인터넷을 이용하기 때문에 종종 NULL 값이 리턴이 되므로 반드시 그것에 대한 예외 처리를 해야 프로그램이 죽는 현상을 막을 수 있습니다.

 

 

예제 코드

 

 

in_addr in;

LPHOSTENT lphost = gethostbyname( "tk.co.kr" );

if( lphost != NULL )    

{

    in.s_addr = ( ( LPIN_ADDR ) lphost->h_addr )->s_addr;

 

    CString strAddr = inet_ntoa( in ); // 변환된 주소를 사용한다.

}

else

{

    in.s_addr = 0;

 

    int error = WSAGetLastError(); // 오류코드를 처리한다.

}

 

 

 

리턴된 error 값은 아래와 같은 오류조회 툴로 확인할 수 있습니다.

 

 

 

오류 코드 : 출처 MSDN 참고

 

Error code

Description

WSANOTINITIALISED

A successful WSAStartup call must occur before using this function.

WSAENETDOWN

The network subsystem has failed.

WSAHOST_NOT_FOUND

An authoritative answer host was not found.

WSATRY_AGAIN

A nonauthoritative host was not found, or the server failure.

WSANO_RECOVERY

A nonrecoverable error occurred.

WSANO_DATA

A valid name exists, but no data record of the requested type exists.

WSAEINPROGRESS

A blocking Winsock call is in progress, or the service provider is still processing a callback function.

WSAEFAULT

The name parameter is not a valid part of the user address space.

WSAEINTR

The socket was closed.