Skip to content

Instantly share code, notes, and snippets.

@alunux
Forked from edufelipe/is_wireless.c
Created April 23, 2017 03:18
Show Gist options
  • Save alunux/ddc80ee5ad52088762a8b53d63522f59 to your computer and use it in GitHub Desktop.
Save alunux/ddc80ee5ad52088762a8b53d63522f59 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment