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