views:

737

answers:

3

I'm wondering how I'd go about getting the:

  • Internal IP address;
  • External IP address; and
  • Default gateway

in Windows (WinSock) and Unix systems.

Thanks in advance,

A: 

Linux:

ifconfig -a gives internal ip
netstat -a   gives default gateway

Windows:

ipconfig /all  gives internal ip
netstat -a gives default gateway

I'm not sure how to definitively determine the external ip in either system

ennuikiller
Sorry, I forgot to mention I meant in C/++ :D
Saul Rennison
I don't see my default gateway in `netstat -a` on either Linux or Windows? I see the list of connections on my machine, including listening ports, but no where on that list do i see my default gateway's hostname or IP address. What am I missing?
mrduclaw
my mistake, netstat -r gives the default gateway
ennuikiller
A: 

There is no general purpose mechanism that works on Windows and UNIX. Under Windows you want to start with GetIfTable(). Under most UNIX systems, try getifaddrs(). Those will give you various things like the IP address of each interface.

I'm not sure how one would go about getting the default gateway. I would guess that it is available via some invocation of sysctl. You might want to start with the source for the netstat utility.

The external public address is something that a computer never knows. The only way is to connect to something on the internet and have it tell you what address you are coming from. This is one of the classic problems with IPNAT.

D.Shawley
+1  A: 

Solved thanks to: http://www.codeguru.com/forum/showthread.php?t=233261


#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>

#pragma comment(lib, "ws2_32.lib")

int main(int nArgumentCount, char **ppArguments)
{
 WSADATA WSAData;

 // Initialize WinSock DLL
 if(WSAStartup(MAKEWORD(1, 0), &WSAData))
 {
  // Error handling
 }

 // Get local host name
 char szHostName[128] = "";

 if(gethostname(szHostName, sizeof(szHostName)))
 {
  // Error handling -> call 'WSAGetLastError()'
 }

 SOCKADDR_IN socketAddress;
 hostent *pHost        = 0;

 // Try to get the host ent
 pHost = gethostbyname(szHostName);
 if(!pHost)
 {
  // Error handling -> call 'WSAGetLastError()'
 }

 char ppszIPAddresses[10][16]; // maximum of ten IP addresses
 for(int iCnt = 0; (pHost->h_addr_list[iCnt]) && (iCnt < 10); ++iCnt)
 {
  memcpy(&socketAddress.sin_addr, pHost->h_addr_list[iCnt], pHost->h_length);
  strcpy(ppszIPAddresses[iCnt], inet_ntoa(socketAddress.sin_addr));

  printf("Found interface address: %s\n", ppszIPAddresses[iCnt]);
 }

 // Cleanup
 WSACleanup();
}
Saul Rennison