c++ - 如何获取(Linux)机器的 IP 地址?

标签 c++ linux networking ip-address

这个问题和之前问的 How can I get the IP Address of a local computer? 差不多-问题。但是我需要找到 Linux 机器的 IP 地址。

那么:我如何 - 在 C++ 中以编程方式 - 检测运行我的应用程序的 linux 服务器的 IP 地址。服务器将至少有两个 IP 地址,我需要一个特定的 IP 地址(给定网络中的一个(公共(public)网络))。

我确信有一个简单的函数可以做到这一点 - 但在哪里?


为了让事情更清楚一点:

  • 服务器显然会有“localhost”:127.0.0.1
  • 服务器将有一个内部(管理)IP 地址:172.16.x.x
  • 服务器将有一个外部(公共(public))IP 地址:80.190.x.x

我需要找到外部 IP 地址来将我的应用程序绑定(bind)到它。显然我也可以绑定(bind)到 INADDR_ANY (实际上这就是我现在所做的)。不过,我更愿意检测公共(public)地址。

最佳答案

我发现 os x 上的 ioctl 解决方案有问题(它符合 POSIX,因此应该类似于 linux)。但是 getifaddress() 会让你轻松地做同样的事情,它在 os x 10.5 上对我来说很好,下面应该是一样的。

我在下面做了一个简单的示例,它将打印机器的所有 IPv4 地址,(您还应该检查 getifaddrs 是否成功,即返回 0)。

我更新了它也显示 IPv6 地址。

#include <stdio.h>      
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h> 
#include <string.h> 
#include <arpa/inet.h>

int main (int argc, const char * argv[]) {
    struct ifaddrs * ifAddrStruct=NULL;
    struct ifaddrs * ifa=NULL;
    void * tmpAddrPtr=NULL;

    getifaddrs(&ifAddrStruct);

    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
        if (!ifa->ifa_addr) {
            continue;
        }
        if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4
            // is a valid IP4 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
            printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); 
        } else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6
            // is a valid IP6 Address
            tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
            char addressBuffer[INET6_ADDRSTRLEN];
            inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
            printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); 
        } 
    }
    if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
    return 0;
}

关于c++ - 如何获取(Linux)机器的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/212528/

相关文章:

networking - 了解内核中的 'struct proto'和 'struct proto_ops'

c - gethostbyname 双网络接口(interface),选择使用哪一个

c++ - 将 lambda 作为模板参数传递 : what type is actually deduced?

c++ - 仅使用 regex_search 返回第一个匹配项

c++ - 无法访问 vector 大小

java - 在启动 Ubuntu 时运行程序

linux - 使用 PowerShell 删除重复行比 WSL 花费更长的时间

c++ - 为什么nullptr不需要标题,而nullptr_t却需要

linux - 是否存在读取自身进程的[堆栈]地址范围的函数?

c - 如何区分以太网和其他以太网?