Determine if a network interface is wireless or wired

后端 未结 4 1415
时光取名叫无心
时光取名叫无心 2021-01-04 09:19

I have a program that has two separate sections: one of them should be executed when the network interface is wireless LAN and the other one when it\'s a wired LAN connectio

4条回答
  •  庸人自扰
    2021-01-04 09:23

    You can call ioctl(fd, SIOCGIWNAME) that returns the wireless extension protocol version, which is only available on interfaces that are wireless.

    int check_wireless(const char* ifname, char* protocol) {
      int sock = -1;
      struct iwreq pwrq;
      memset(&pwrq, 0, sizeof(pwrq));
      strncpy(pwrq.ifr_name, ifname, IFNAMSIZ);
    
      if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        return 0;
      }
    
      if (ioctl(sock, SIOCGIWNAME, &pwrq) != -1) {
        if (protocol) strncpy(protocol, pwrq.u.name, IFNAMSIZ);
        close(sock);
        return 1;
      }
    
      close(sock);
      return 0;
    }
    

    For a complete example see: https://gist.github.com/edufelipe/6108057

提交回复
热议问题