C++ Get Local IP address,differentiate between the VPN and local network
My computer is connected to the local network(ethernet adapter) with ip addre开发者_StackOverflowss 10.3.3.3 and it is connected with my VPN(PPP adapter) with the IP address 172.4.0.70
Now, how can I get my local IP(10.3.3.3) programmatically?
I had tested using the following code.
But I can't differentiate between the VPN and local network, any help will be much appreciated.
WSAData .....;
char* address=NULL;
getLocalIP(&address);
int getLocalIP(char** raddr)
{
char ac[80];
if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)
{
return 1;
}
struct hostent *phe = gethostbyname(ac);
if (phe == 0)
{
return 1;
}
for (int i = 0; phe->h_addr_list[i] != 0; ++i)
{
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
//How can I tell if it's not VPN?
//if (isnotVPN){
*raddr=inet_ntoa(addr); //<== ip address
//break;}
}
return 0;
}
c++ VS2008 Win7 64bits
Few years later... Just ran into the same issue, and figured out a solution. You can use GetAdaptersInfo() to get all the local adapters, and then cycle through the list and pick the first with a valid subnet mask and a default gateway (my VPN adapter didn't have one). If you have both WiFi and Ethernet with default gateways!!, I guess you can use the Type field to pick Ethernet..
This is similar to the sample code for GetAdaptersInfo() on MSDN.
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter = NULL;
DWORD dwRetVal = 0;
PIP_ADDR_STRING pIPAddrString, pIPGwString;
ULONG ulOutBufLen;
pAdapterInfo = (IP_ADAPTER_INFO *)malloc( sizeof( IP_ADAPTER_INFO ) );
if( !pAdapterInfo ); //Malloc Failed
ulOutBufLen = sizeof( IP_ADAPTER_INFO );
if( GetAdaptersInfo( pAdapterInfo, &ulOutBufLen ) == ERROR_BUFFER_OVERFLOW ) {
free( pAdapterInfo );
pAdapterInfo = (IP_ADAPTER_INFO *)malloc( ulOutBufLen );
if( !pAdapterInfo ); //Malloc Failed
}
if( ( dwRetVal = GetAdaptersInfo( pAdapterInfo, &ulOutBufLen) ) == NO_ERROR ) {
pAdapter = pAdapterInfo;
while( pAdapter ) {
pIPAddrString = &pAdapter->IpAddressList;
pIPGwString = &pAdapter->GatewayList;
while( pIPAddrString ) {
ULONG ulIPMask, ulIPGateway;
ulIPMask = ntohl( inet_addr( pIPAddrString->IpMask.String ) );
ulIPGateway = ntohl( inet_addr( pIPGwString->IpAddress.String ) );
if( !ulIPMask ) {
pIPAddrString = pIPAddrString->Next;
continue;
}
//First adapter with a default gateway
if ( ulIPGateway ) {
strncpy( GETYOURSTRINGHERE, pIPAddrString->IpAddress.String, sizeof(pIPAddrString->IpAddress.String));
free( pAdapterInfo );
return;
}
pIPAddrString = pIPAddrString->Next;
}
pAdapter = pAdapter->Next;
}
}
if ( pAdapterInfo )
free( pAdapterInfo );
精彩评论