windows 如何获取 UPnP 的内部 IP、外部 IP 和默认网关
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1738733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get internal IP, external IP and default gateway for UPnP
提问by Saul
I'm wondering how I'd go about getting the:
我想知道如何获得:
- Internal IP address;
- External IP address; and
- Default gateway
- 内部IP地址;
- 外部IP地址;和
- 默认网关
in Windows (WinSock) and Unix systems.
在 Windows (WinSock) 和 Unix 系统中。
Thanks in advance,
提前致谢,
回答by D.Shawley
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.
没有适用于 Windows 和 UNIX 的通用机制。在 Windows 下,您希望以GetIfTable()
. 在大多数 UNIX 系统下,尝试getifaddrs()
. 这些将为您提供各种信息,例如每个接口的 IP 地址。
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.
我不确定如何获得默认网关。我猜它可以通过调用sysctl
. 您可能希望从netstat 实用程序的源代码开始。
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.
外部公共地址是计算机永远不知道的东西。唯一的方法是连接到 Internet 上的某些内容,并让它告诉您来自哪个地址。这是 IPNAT 的经典问题之一。
回答by Saul
Solved thanks to: http://www.codeguru.com/forum/showthread.php?t=233261
解决感谢: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();
}
回答by ennuikiller
Linux:
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
我不确定如何在任一系统中明确确定外部 IP