Qt之Linux-C 判断网络是否连接

#include 
#include 
#include 


struct caddr_d {
        __uint32_t      cmd;    
        __uint32_t      data;
};
 
int main(int , char* [])
{    
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == -1) return 0;

    struct ifreq ifr;
    struct caddr_d caddr;
    memset(&ifr, 0, sizeof(struct ifreq));
    strcpy(ifr.ifr_ifrn.ifrn_name, "eth0");    //根据自己网卡信息填写是否是eth0

    caddr.cmd = 0x0000000a;
    ifr.ifr_ifru.ifru_data = (caddr_t)&caddr;

    int err = ioctl(fd, 0x8946, &ifr);
    if (err == 0)
    {
        if (caddr.data)
        {
            // 连接
        }
        else
        {
            // 没连接
        }
    }
    else if (errno != EOPNOTSUPP) 
    {
        // 网线拔掉
        perror("Cannot get link status");
    }

   return 0;
}

 

你可能感兴趣的:(Network)