How to check if interface is up

我与影子孤独终老i 提交于 2019-12-03 07:27:47

Answer was simple: I used the bitwise OR (|) operator instead of the AND (&) operator. Fixed code is:

bool is_interface_online(std::string interface) {
    struct ifreq ifr;
    int sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, interface.c_str());
    if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
            perror("SIOCGIFFLAGS");
    }
    close(sock);
    return !!(ifr.ifr_flags & IFF_UP);
}

Have you considered using the strace command to see how ifconfig works? you can even see what parameters are passed to functions and other interesting details of how ifconfig works ..

If you care about the up/down state of the interface you might want to use the "IFF_RUNNING" flag instead of the "IFF_UP" flag provided by the current answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!