inet_ntop함수는 xp에서 사용할 수 없는 문제 해결

inet_ntop함수는 소켓의 ip주소를 얻어오는 함수인데 xp에서 동작하지 않는다.


다른 함수를 찾아봐야 하는데,


그 주인공은 WSAAddressToString 함수가 되겠다.


사용 코드 예제는 유니코드와 안시코드 모두 동작할 수 있는 버전으로 구현하였다.

// GetIPAddressFromSocket.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> #include <winsock2.h> #include <ws2tcpip.h> #include <mswsock.h> #pragma comment(lib, "ws2_32.lib") namespace std { #ifdef UNICODE typedef wstring tstring; #else typedef string tstring; #endif } bool getSocketAddress(SOCKET socket, __out std::tstring& address) { TCHAR buf[INET_ADDRSTRLEN]; SOCKADDR_IN name; socklen_t len = sizeof(name); if (getpeername(socket, (struct sockaddr *)&name, &len) != 0) { return false; } DWORD cnt = sizeof(buf); if (WSAAddressToString((struct sockaddr*) &name, sizeof(SOCKADDR_IN), 0, buf, &cnt) != 0) { return false; } address = buf; return true; } SOCKET Connect(const std::tstring& ip, WORD port) { SOCKET connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { return 0; } // Connect to server. SOCKADDR_IN sockaddr; INT addressSize = 0; ZeroMemory( &sockaddr,sizeof( SOCKADDR_IN ) ); sockaddr.sin_family = AF_INET; addressSize = sizeof(sockaddr); WSAStringToAddress((TCHAR*)ip.c_str(), AF_INET, NULL, (SOCKADDR*)&sockaddr, &addressSize); sockaddr.sin_port = htons( port ); int iResult = connect( connectSocket, (SOCKADDR*)&sockaddr, addressSize); if (iResult == SOCKET_ERROR) { return 0; } return connectSocket; } void Disconnect(SOCKET socket) { shutdown(socket, SD_SEND); closesocket(socket); } bool NetworkStartup() { WSADATA wsaData; if (0 != WSAStartup(WINSOCK_VERSION, &wsaData)) { return false; } return true; } void NetworkFinish() { WSACleanup(); } int _tmain(int argc, _TCHAR* argv[]) { if (false == NetworkStartup()) { return 0; } SOCKET connected_socket = Connect(_T("74.125.128.104"), 80); std::tstring address; if (true == getSocketAddress(connected_socket, address)) { _tprintf(_T("socket's ip address(%s)"), address.c_str()); } Disconnect(connected_socket); NetworkFinish(); return 0; }