13

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?

jww
  • 90,984
  • 81
  • 374
  • 818
deinocheirus
  • 1,743
  • 3
  • 24
  • 41
  • What if there are several network interfaces that are all being used in parallel? – unwind Sep 24 '12 at 14:20
  • The wireless part of the code will be executed for those that are wireless and the wired part for those that are wired, in parallel. – deinocheirus Sep 24 '12 at 14:25

4 Answers4

9

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.

Dan Aloni
  • 3,818
  • 19
  • 28
8

You can use the iwconfig command from the command line:

$ iwconfig
lo        no wireless extensions.
eth0      no wireless extensions.

If you need to use it from C, as @opaque's link above explains, get the sources or use strace to see which ioctls() you need to use:

ioctl(3, SIOCGIWNAME, 0x7fff82c0d040)   = -1 EOPNOTSUPP (Operation not supported)
ioctl(3, SIOCGIFFLAGS, {ifr_name="lo", ifr_flags=IFF_UP|IFF_LOOPBACK|IFF_RUNNING}) = 0
write(2, "lo        no wireless extensions"..., 35lo        no wireless extensions.

) = 35
ioctl(3, SIOCGIWNAME, 0x7fff82c0d040)   = -1 EOPNOTSUPP (Operation not supported)
ioctl(3, SIOCGIFFLAGS, {ifr_name="eth0", ifr_flags=IFF_UP|IFF_BROADCAST|IFF_RUNNING|IFF_MULTICAST}) = 0
write(2, "eth0      no wireless extensions"..., 35eth0      no wireless extensions.

) = 35

See SIOCGIWNAME usage:

#define SIOCGIWNAME 0x8B01 /* get name == wireless protocol */
/* SIOCGIWNAME is used to verify the presence of Wireless Extensions.
* Common values : "IEEE 802.11-DS", "IEEE 802.11-FH", "IEEE 802.11b"...
Andreas Fester
  • 35,119
  • 7
  • 92
  • 115
8

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

Edu Felipe
  • 9,728
  • 13
  • 43
  • 41
1

If you target NetworkManager then take a look at its API, C examples and NMDeviceType.

Maxim Egorushkin
  • 125,859
  • 15
  • 164
  • 254