How do i capture ip address of a machine having more than one ip?
Thanx for any kind of help.
Regards,
shail2k4
Printable View
How do i capture ip address of a machine having more than one ip?
Thanx for any kind of help.
Regards,
shail2k4
How to get the local IP address(es)Quote:
Originally Posted by shail2k4
Doesn't GetIpAddrTable work?
GetIpAddrTable
Do you want the internal or external IP's?
Also see GetAdaptersInfo and GetAdaptersAddresses.
the code below is partly based on various internet resources, partly my own. simply call the methods, passing them parameters to store return values.
link: iphlpapi.lib
stdafx.h: #include <afxsock.h> // MFC socket extensions
global: #include <iphlpapi.h> // internet
#include <afxinet.h>
Code:// determine all LAN IP addresses of this machine into CStringArray reference parameter
void FindLANIPAddresses( CStringArray & stringArray )
{
const DWORD loopbackAddress = 16777343; // 127.0.0.1 - to be ignored
struct in_addr ipAddress;
PMIB_IPADDRTABLE ipAddressTable = new MIB_IPADDRTABLE;
ULONG size = 0;
// determine the necessary size of ipAddressTable into 'size'
if( GetIpAddrTable( ipAddressTable, &size, 0 ) == ERROR_INSUFFICIENT_BUFFER )
{
delete [] ipAddressTable;
ipAddressTable = ( PMIB_IPADDRTABLE ) malloc( size );
}
// now 'size' is correct, so fill in ipAddressTable
if( GetIpAddrTable( ipAddressTable, &size, TRUE ) != NO_ERROR )
return; // error
// convert ip to string , get rid of blank and loopback entries
DWORD tempIP;
for( int i = 0; i < ( int )ipAddressTable->dwNumEntries; i++ )
{
tempIP = ipAddressTable->table[ i ].dwAddr;
if( tempIP != 0 && tempIP != loopbackAddress )
{
memmove ( &ipAddress, &tempIP, 4 );
stringArray.Add( inet_ntoa ( ipAddress ) );
}
}
delete [] ipAddressTable;
} // end FindLANIPAddresses
// determine WAN IP address of this machine or router/gateway into CString parameter
void FindWANIPAddress( CString & string )
{
DWORD queryReturnValue = 0;
CInternetSession *pSession = new CInternetSession(_T("GetIP number") );
CHttpFile * pFile;
try
{
pFile = ( CHttpFile * ) pSession->OpenURL( "http://checkip.dyndns.org/" );
}
catch (CInternetException* pEx)
{
pEx->Delete();
pFile->Close();
delete pFile;
delete pSession;
return; // could not open URL
}
pFile->QueryInfoStatusCode(queryReturnValue);
if( queryReturnValue == 200 ) // Yes! - success status code: 200
{
char * fileBuffer = new char[ 1024 ];
char * originalFileBuffer = fileBuffer;
char ipBuffer[ 16 ]; // holds extracted IP address
pFile->Read( fileBuffer, 1024 ); // read first 1024 bytes of HTML.
if ( fileBuffer )
{
int start = strcspn( fileBuffer, "1234567890" );
fileBuffer += start;
int end = strspn( fileBuffer, "0123456789." );
strncpy( ipBuffer, fileBuffer, end );
ipBuffer[ end ] = '\0';
string = ipBuffer; // place IP number in passed parameter
}
delete [] originalFileBuffer;
}
pFile->Close();
delete pFile;
delete pSession;
} // end FindWANIPAddress