How to check if interface is up

前端 未结 3 771
情歌与酒
情歌与酒 2020-12-31 15:19

Title pretty much says it all. If I run ifconfig, I get this:

eth0: flags=4163  mtu 1500
    inet -snip-           


        
相关标签:
3条回答
  • 2020-12-31 15:44

    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.

    0 讨论(0)
  • 2020-12-31 15:52

    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);
    }
    
    0 讨论(0)
  • 2020-12-31 15:58

    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 ..

    0 讨论(0)
提交回复
热议问题