summaryrefslogtreecommitdiff
path: root/src/get_ip_addr.c
blob: 354ae08696f33768825e01c5c1bdad9cf9fa1119 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// vim:ts=8:expandtab
#include <net/if.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <ifaddrs.h>

#include "i3status.h"

/*
 * Return the IP address for the given interface or "no IP" if the
 * interface is up and running but hasn't got an IP address yet
 *
 */
const char *get_ip_addr(const char *interface) {
        static char part[512];
        socklen_t len = sizeof(struct sockaddr_in);
        memset(part, 0, sizeof(part));

        struct ifaddrs *ifaddr, *addrp;

        getifaddrs(&ifaddr);

        if (ifaddr == NULL) {
                (void)snprintf(part, sizeof(part), "E: down");
                return part;
        }

        addrp = ifaddr;

        /* Skip until we are at the AF_INET address of eth_interface */
        for (addrp = ifaddr;

             (addrp != NULL &&
              (strcmp(addrp->ifa_name, eth_interface) != 0 ||
               addrp->ifa_addr == NULL ||
               addrp->ifa_addr->sa_family != AF_INET));

             addrp = addrp->ifa_next) {
                /* Check if the interface is down */
                if (strcmp(addrp->ifa_name, eth_interface) == 0 &&
                    (addrp->ifa_flags & IFF_RUNNING) == 0)
                        return NULL;
        }

        if (addrp == NULL)
                return "no IP";

        int ret;
        if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
                fprintf(stderr, "getnameinfo(): %s\n", gai_strerror(ret));
                return "no IP";
        }

        return part;
}