Xinqi Bao's Git

Fix coding style
[slstatus.git] / components / wifi.c
1 /* See LICENSE file for copyright and license details. */
2 #if defined(__linux__)
3 #include <errno.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,
27 "/operstate");
28 if (!(fp = fopen(path, "r"))) {
29 fprintf(stderr, "fopen '%s': %s\n", path,
30 strerror(errno));
31 return NULL;
32 }
33 p = fgets(status, 5, fp);
34 fclose(fp);
35 if(!p || strcmp(status, "up\n") != 0) {
36 return NULL;
37 }
38
39 if (!(fp = fopen("/proc/net/wireless", "r"))) {
40 fprintf(stderr, "fopen '/proc/net/wireless': %s\n",
41 strerror(errno));
42 return NULL;
43 }
44
45 for (i = 0; i < 3; i++) {
46 if (!(p = fgets(buf, sizeof(buf) - 1, fp)))
47 break;
48 }
49 fclose(fp);
50 if (i < 2 || !p) {
51 return NULL;
52 }
53
54 if (!(datastart = strstr(buf, iface))) {
55 return NULL;
56 }
57
58 datastart = (datastart+(strlen(iface)+1));
59 sscanf(datastart + 1, " %*d %d %*d %*d\t\t %*d\t "
60 "%*d\t\t%*d\t\t %*d\t %*d\t\t %*d", &cur);
61
62 perc = (float)cur / total * 100.0;
63
64 return bprintf("%.0f", perc);
65 }
66
67 const char *
68 wifi_essid(const char *iface)
69 {
70 static char id[IW_ESSID_MAX_SIZE+1];
71 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
72 struct iwreq wreq;
73
74 memset(&wreq, 0, sizeof(struct iwreq));
75 wreq.u.essid.length = IW_ESSID_MAX_SIZE+1;
76 snprintf(wreq.ifr_name, sizeof(wreq.ifr_name), "%s", iface);
77
78 if (sockfd < 0) {
79 fprintf(stderr, "socket 'AF_INET': %s\n",
80 strerror(errno));
81 return NULL;
82 }
83 wreq.u.essid.pointer = id;
84 if (ioctl(sockfd,SIOCGIWESSID, &wreq) < 0) {
85 fprintf(stderr, "ioctl 'SIOCGIWESSID': %s\n", strerror(errno));
86 close(sockfd);
87 return NULL;
88 }
89
90 close(sockfd);
91
92 if (!strcmp(id, "")) {
93 return NULL;
94 }
95
96 return id;
97 }
98 #elif defined(__OpenBSD__)
99 /* unimplemented */
100 #endif