Xinqi Bao's Git

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