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;
}
@jorgeas80
Copy link

That's great. I just need an equivalent that works in Windows and Mac OS X. I guess this could work on Mac too. So, the Windows part looks the harder one...

@alunux
Copy link

alunux commented Jun 8, 2017

Great example. Can you add license header to your example?

@matteyeux
Copy link

Hey this thing is great, is there a way to check if interface is ethernet instead of wireless ?

@MisterBianco
Copy link

MisterBianco commented May 9, 2018

Hey, just a quick question, why does every call require a fresh socket? Is there a way to reuse them by instantiating the socket in the main function and passing it as a pointer to is_wireless? That would be cool and save several calls to open a socket.

Ha nm, I figured it out I'm a dumbass.

@MafiaBoys
Copy link

We have to go back to machine language so that we can do something more efficient and credible because I don't trust the available c libraries.

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