Xinqi Bao's Git

updated ram_total and ram_free (obsd)
[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 <limits.h>
6 #include <linux/wireless.h>
7 #include <sys/socket.h>
8 #include <stdio.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 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,
26 "/operstate");
27 if (!(fp = fopen(path, "r"))) {
28 fprintf(stderr, "fopen '%s': %s\n", path,
29 strerror(errno));
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 if (!(fp = fopen("/proc/net/wireless", "r"))) {
39 fprintf(stderr, "fopen '/proc/net/wireless': %s\n",
40 strerror(errno));
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
53 if (!(datastart = strstr(buf, iface))) {
54 return NULL;
55 }
56
57 datastart = (datastart+(strlen(iface)+1));
58 sscanf(datastart + 1, " %*d %d %*d %*d\t\t %*d\t "
59 "%*d\t\t%*d\t\t %*d\t %*d\t\t %*d", &cur);
60
61 return bprintf("%d", (int)((float)cur / total * 100));
62 }
63
64 const char *
65 wifi_essid(const char *iface)
66 {
67 static char id[IW_ESSID_MAX_SIZE+1];
68 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
69 struct iwreq wreq;
70
71 memset(&wreq, 0, sizeof(struct iwreq));
72 wreq.u.essid.length = IW_ESSID_MAX_SIZE+1;
73 snprintf(wreq.ifr_name, sizeof(wreq.ifr_name), "%s", iface);
74
75 if (sockfd < 0) {
76 fprintf(stderr, "socket 'AF_INET': %s\n",
77 strerror(errno));
78 return NULL;
79 }
80 wreq.u.essid.pointer = id;
81 if (ioctl(sockfd,SIOCGIWESSID, &wreq) < 0) {
82 fprintf(stderr, "ioctl 'SIOCGIWESSID': %s\n", strerror(errno));
83 close(sockfd);
84 return NULL;
85 }
86
87 close(sockfd);
88
89 if (!strcmp(id, "")) {
90 return NULL;
91 }
92
93 return id;
94 }
95 #elif defined(__OpenBSD__)
96 /* unimplemented */
97 #endif