]> git.sur5r.net Git - i3/i3status/blob - src/get_ip_addr.c
Add modelines and retab! all files
[i3/i3status] / src / get_ip_addr.c
1 // vim:ts=8:expandtab
2 #include <net/if.h>
3 #include <sys/socket.h>
4 #include <sys/ioctl.h>
5 #include <sys/types.h>
6 #include <stdlib.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <netdb.h>
10
11 #include "i3status.h"
12
13 /*
14  * Return the IP address for the given interface or "no IP" if the
15  * interface is up and running but hasn't got an IP address yet
16  *
17  */
18 const char *get_ip_addr(const char *interface) {
19         static char part[512];
20         struct ifreq ifr;
21         socklen_t len = sizeof(struct sockaddr_in);
22         memset(part, 0, sizeof(part));
23
24         /* First check if the interface is running */
25         (void)strcpy(ifr.ifr_name, interface);
26         if (ioctl(general_socket, SIOCGIFFLAGS, &ifr) < 0 ||
27             !(ifr.ifr_flags & IFF_RUNNING))
28                 return NULL;
29
30         /* Interface is up, get the IP address */
31         (void)strcpy(ifr.ifr_name, interface);
32         ifr.ifr_addr.sa_family = AF_INET;
33         if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
34                 return "no IP";
35
36         int ret;
37         if ((ret = getnameinfo(&ifr.ifr_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
38                 fprintf(stderr, "getnameinfo(): %s\n", gai_strerror(ret));
39                 return "no IP";
40         }
41
42         return part;
43 }
44