Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Fetching IP address

Status
Not open for further replies.

onair

Programmer
Nov 29, 2000
1
DK
HI

I have a problem fething the machines local IP address. I don´t seem to find any network API suitable. I know that it can be fetched from "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\..." but can´t be used in my situation.

Thanks,
mp
 
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <winsock2.h>

#pragma comment( lib,&quot;wsock32.lib&quot; )

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 << &quot;Local IP: &quot; << sIP <<
std::endl;
return 0;
}

int GetIPAddress( LPCSTR lpHostName,LPSTR lpszIPAddress )
{
LPSTR lpAddr;
struct hostent FAR *lpHostEnt=gethostbyname( lpHostName );

if( !lpHostEnt )
{
strcpy( lpszIPAddress,&quot;&quot; );
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=&quot;Not available\n&quot;; */
}
return 0;
}

int GetLocalHostName( LPSTR lpszHostName )
{
char szHostName[256];
int nRetCode;

nRetCode=gethostname( szHostName,sizeof( szHostName ) );
if( nRetCode != 0 )
{
strcpy( lpszHostName,&quot;Not available\n&quot; );
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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top