Click to See Complete Forum and Search --> : getting the IP address


gabirata
July 15th, 2006, 11:06 AM
How can I get the local IP address?

philkr
July 15th, 2006, 12:57 PM
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock.h>
#include <cstdio>
#pragma comment(lib, "wsock32.lib")

int main()
{
WSADATA dWinSock;
char szHostname[MAX_PATH] = {0};
hostent* pHost = NULL;

WSAStartup(MAKEWORD(1, 1), &dWinSock);
gethostname(szHostname, sizeof(szHostname));
pHost = gethostbyname(szHostname);
// all local IP address are now accessible through pHost->h_addr_list array
std::printf("%d.%d.%d.%d\n", (BYTE)pHost->h_addr_list[0][0], (BYTE)pHost->h_addr_list[0][1], (BYTE)pHost->h_addr_list[0][2], (BYTE)pHost->h_addr_list[0][3]);
WSACleanup();
return 0;
}