【问题标题】:How to get the local ip of eth0 using C++?如何使用 C++ 获取 eth0 的本地 ip?
【发布时间】:2014-12-25 02:53:06
【问题描述】:

我想在本地网络中查找 eth0 的 IP 地址(如果电缆已插入),否则返回环回 IP (127.0.0.1)。所以,我尝试了以下代码:

struct in_addr getCurrentIP() {
    int fd=0;
    struct ifreq ifr;
    struct in_addr IP;
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
    if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
        perror("SIOCGIFFLAGS");}
    if ((ifr.ifr_flags & IFF_UP)){
        ioctl(fd, SIOCGIFADDR, &ifr);
        close(fd);
        IP = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
    } else {
        close(fd);
        inet_aton ("127.0.0.1",&IP);
    }
    return  IP;
}

在我拔掉以太网电缆之前,这段代码可以正常工作。然后,它返回任意IP

PS 我连接到提供动态 IP 的网络(即使用 DHCP)。

【问题讨论】:

  • 在绑定到它之前,您可能需要查询实际状态(linked)。
  • 你是对的,这就是我在 if-else 语句中尝试做的事情。我尝试使用 if ((ifr.ifr_flags & IFF_UP & IFF_RUNNING)) 来检查 IFF_RUNNING,对于 IFF_POINTOPOINT 也是如此,但它始终返回 false(即在两种情况下都重定向到环回)。
  • 考虑使用 popen() 来运行 ifconfig。通常,Ubuntu 为 eth0 报告 10 行配置,为 lo 报告 9 行。每个部分都包含“inet addr”和有关链接的一些状态信息。链接断开后,eth0 ifconfig 部分的第 2 行不再有 inet addr(但仍报告 lo inet addr)。
  • 是的@DOUGLASO.MOEN,这可以做到。第二行始终用于 IPV4 地址。但应该有更好的解决方案。假设的解决方案会更可靠。
  • 如果eth0有多个IP地址,代码应该怎么做?如果机器的 eth1 处于活动状态但 eth0 处于非活动状态怎么办?

标签: c++ sockets networking


【解决方案1】:

我解决了,这就是解决方案:

struct in_addr getCurrentIP() {
    int fd=0;
    struct ifreq ifr;
    struct in_addr IP;
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
    if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
        perror("SIOCGIFFLAGS");}
    if ((ifr.ifr_flags & IFF_UP) && (ifr.ifr_flags & IFF_RUNNING)){
        ioctl(fd, SIOCGIFADDR, &ifr);
        close(fd);
        IP = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
    } else {
        close(fd);
        inet_aton ("127.0.0.1",&IP);
    }
    return  IP;
}

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2011-10-09
    相关资源
    最近更新 更多