Xinqi Bao's Git

More robust preprocessor switches
[slstatus.git] / components / wifi.c
1 /* See LICENSE file for copyright and license details. */
2 #if defined(__linux__)
3 #include <err.h>
4 #include <ifaddrs.h>
5 #include <linux/wireless.h>
6 #include <sys/socket.h>
7 #include <stdio.h>
8 #include <limits.h>
9 #include <string.h>
10 #include <sys/ioctl.h>
11 #include <unistd.h>
12
13 #include "../util.h"
14
15 const char *
16 wifi_perc(const char *iface)
17 {
18 int i, cur;
19 float perc;
20 int total = 70; /* the max of /proc/net/wireless */
21 char *p, *datastart;
22 char path[PATH_MAX];
23 char status[5];
24 FILE *fp;
25
26 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/net/", iface, "/operstate");
27 fp = fopen(path, "r");
28 if (fp == NULL) {
29 warn("Failed to open file %s", path);
30 return NULL;
31 }
32 p = fgets(status, 5, fp);
33 fclose(fp);
34 if(!p || strcmp(status, "up\n") != 0) {
35 return NULL;
36 }
37
38 fp = fopen("/proc/net/wireless", "r");
39 if (fp == NULL) {
40 warn("Failed to open file /proc/net/wireless");
41 return NULL;
42 }
43
44 for (i = 0; i < 3; i++) {
45 if (!(p = fgets(buf, sizeof(buf) - 1, fp)))
46 break;
47 }
48 fclose(fp);
49 if (i < 2 || !p)
50 return NULL;
51
52 if ((datastart = strstr(buf, iface)) == NULL)
53 return NULL;
54
55 datastart = (datastart+(strlen(iface)+1));
56 sscanf(datastart + 1, " %*d %d %*d %*d %*d %*d %*d %*d %*d %*d", &cur);
57
58 perc = (float)cur / total * 100.0;
59
60 return bprintf("%.0f", perc);
61 }
62
63 const char *
64 wifi_essid(const char *iface)
65 {
66 static char id[IW_ESSID_MAX_SIZE+1];
67 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
68 struct iwreq wreq;
69
70 memset(&wreq, 0, sizeof(struct iwreq));
71 wreq.u.essid.length = IW_ESSID_MAX_SIZE+1;
72 snprintf(wreq.ifr_name, sizeof(wreq.ifr_name), "%s", iface);
73
74 if (sockfd == -1) {
75 warn("Failed to get ESSID for interface %s", iface);
76 return NULL;
77 }
78 wreq.u.essid.pointer = id;
79 if (ioctl(sockfd,SIOCGIWESSID, &wreq) == -1) {
80 warn("Failed to get ESSID for interface %s", iface);
81 close(sockfd);
82 return NULL;
83 }
84
85 close(sockfd);
86
87 if (strcmp(id, "") == 0)
88 return NULL;
89 else
90 return id;
91 }
92 #endif