问题
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,
回答1:
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.
回答2:
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();
}
回答3:
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
来源:https://stackoverflow.com/questions/1738733/how-to-get-internal-ip-external-ip-and-default-gateway-for-upnp