如何获得内部IP,外部IP和默认网关的UPnP
解决了感谢: 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();
}
的Linux:
ifconfig -a gives internal ip
netstat -a gives default gateway
的Windows:
ipconfig /all gives internal ip
netstat -a gives default gateway
我不知道如何明确地确定在任一系统
对不起,我忘了提及我的意思是在C/++中:D – Saul 2009-11-17 00:01:45
在Linux或Windows上,我没有在'netstat -a'中看到我的默认网关?我看到我机器上的连接列表,包括监听端口,但没有在列表中的哪个位置显示默认网关的主机名或IP地址。我错过了什么? – mrduclaw 2010-09-15 14:04:49
我的错误,netstat -r给出默认网关 – ennuikiller 2010-09-15 21:40:56
有外部IP不是在Windows和UNIX上运行的通用机制。在Windows下,你想从GetIfTable()
开始。在大多数UNIX系统下,请尝试getifaddrs()
。这些将给你各种东西,如每个接口的IP地址。
我不确定如何获取默认网关。我猜想它可以通过调用sysctl
。您可能需要从the netstat utility的来源开始。
外部公共地址是电脑从来不知道的东西。唯一的办法是连接到互联网上的东西,并告诉你你来自哪个地址。这是IPNAT的一个经典问题。
要知道,一台机器可以有几个不同的IP地址。 – pmg 2009-11-15 20:46:45