#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <winsock2.h>
#pragma comment( lib,"wsock32.lib" )
int GetIPAddress( LPCSTR lpHostName,LPSTR lpszIPAddress );
int GetLocalHostName( LPSTR lpszHostName );
int WinSock32CleanUp();
int WinSock32StartUp();
int main()
{
char sHostName[MAX_PATH];
char sIP[MAX_PATH];
WinSock32StartUp();
GetLocalHostName( sHostName );
GetIPAddress( sHostName,sIP );
WinSock32CleanUp();
std::cout << "Local IP: " << sIP <<
std::endl;
return 0;
}
int GetIPAddress( LPCSTR lpHostName,LPSTR lpszIPAddress )
{
LPSTR lpAddr;
struct hostent FAR *lpHostEnt=gethostbyname( lpHostName );
if( !lpHostEnt )
{
strcpy( lpszIPAddress,"" );
return WSAGetLastError();
}
lpAddr=lpHostEnt->h_addr_list[0];
if( lpAddr )
{
struct in_addr inAddr;
memmove( &inAddr,lpAddr,4 );
strcpy( lpszIPAddress,inet_ntoa( inAddr ) );
/* if( sIPAddress->empty() )
*sIPAddress="Not available\n"; */
}
return 0;
}
int GetLocalHostName( LPSTR lpszHostName )
{
char szHostName[256];
int nRetCode;
nRetCode=gethostname( szHostName,sizeof( szHostName ) );
if( nRetCode != 0 )
{
strcpy( lpszHostName,"Not available\n" );
return WSAGetLastError();
}
strcpy( lpszHostName,szHostName );
return 0;
}
int WinSock32CleanUp()
{
int nRetCode;
nRetCode=WSACleanup();
if( nRetCode != 0 )
return WSAGetLastError();
return 0;
}
int WinSock32StartUp()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD( 2, 0 );
err=WSAStartup( wVersionRequested,&wsaData );
/* couldn't find a usable WinSock DLL. */
if( err != 0 ) return err;
/*
Confirm that the WinSock DLL supports 2.0.
Note that if the DLL supports versions greater
than 2.0 in addition to 2.0, it will still return
2.0 in wVersion since that is the version we
requested.
*/
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 0 )
{
/* couldn't find a usable WinSock DLL. */
WSACleanup( );
return WSAVERNOTSUPPORTED;
}
/* The WinSock DLL is acceptable */
return 0;
}
You can go through good old winsock to obtain your local IP address. Mike L.G.
mlg400@linuxmail.org