Created
July 29, 2013 21:33
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
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
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.