Skip to content

Instantly share code, notes, and snippets.

@edufelipe
Created July 29, 2013 21:33
Show Gist options
  • Save edufelipe/6108057 to your computer and use it in GitHub Desktop.
Save edufelipe/6108057 to your computer and use it in GitHub Desktop.
C example code to list all network interfaces and check whether they are wireless or not. Linux only. Tested on Ubuntu 10.04 and 12.04, but should be compatible with pretty much everything out there.
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <ifaddrs.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/wireless.h>
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;
}
int main(int argc, char const *argv[]) {
struct ifaddrs *ifaddr, *ifa;
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
return -1;
}
/* Walk through linked list, maintaining head pointer so we
can free list later */
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
char protocol[IFNAMSIZ] = {0};
if (ifa->ifa_addr == NULL ||
ifa->ifa_addr->sa_family != AF_PACKET) continue;
if (check_wireless(ifa->ifa_name, protocol)) {
printf("interface %s is wireless: %s\n", ifa->ifa_name, protocol);
} else {
printf("interface %s is not wireless\n", ifa->ifa_name);
}
}
freeifaddrs(ifaddr);
return 0;
}
@edufelipe
Copy link
Author

@32th-System this code is from 12 years ago. This didn't exist for Ubuntu 10.04 or 12.04, which what I has using at the time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment