Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a network interface is wireless or wired

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 connection. How can I know that inside of my program? What function should I use to get that information?

like image 957
deinocheirus Avatar asked Sep 24 '12 14:09

deinocheirus


2 Answers

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

like image 87
Edu Felipe Avatar answered Oct 17 '22 08:10

Edu Felipe


If your device name is NETDEVICE, a check of the existence of the /sys/class/net/NETDEVICE/wireless directory is a predicate you can use. This is a Linux-only approach, though, and it assumes that /sys is mounted, which is almost always the normal case. It's also easier to employ this method from scripts, rather than dealing with ioctl()s.

like image 22
Dan Aloni Avatar answered Oct 17 '22 06:10

Dan Aloni