How to get internal IP, external IP and default ga

2019-06-11 10:50发布

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,

3条回答
我只想做你的唯一
2楼-- · 2019-06-11 11:24

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.

查看更多
老娘就宠你
3楼-- · 2019-06-11 11:27

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

查看更多
Melony?
4楼-- · 2019-06-11 11:37

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();
}
查看更多
登录 后发表回答