using C code to get same info as ifconfig

前端 未结 6 785
醉话见心
醉话见心 2020-11-27 03:15

Is there a way in Linux, using C code, to get the same information that \"ifconfig eth0\" would return? I\'m interested in things like IP address, link status, and MAC addr

6条回答
  •  醉梦人生
    2020-11-27 03:55

    Here is how I get MAC and MTU in my code:

    void getMACAddress(std::string _iface,unsigned char MAC[6]) {
            int fd = socket(AF_INET, SOCK_DGRAM, 0);
            struct ifreq ifr;
            ifr.ifr_addr.sa_family = AF_INET;
            strncpy(ifr.ifr_name , _iface.c_str() , IFNAMSIZ-1);
            ioctl(fd, SIOCGIFHWADDR, &ifr);
            for(unsigned int i=0;i<6;i++)
                MAC[i] = ifr.ifr_hwaddr.sa_data[i];
            ioctl(fd, SIOCGIFMTU, &ifr);
            close(fd);
            printf("MTU: %d\n",ifr.ifr_mtu);
            printf("MAC:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",MAC[0],MAC[1],MAC[2],MAC[3],MAC[4],MAC[5]);
        }
    

提交回复
热议问题