From 6fda988f360b3145d5772b6964f336dd652357ea Mon Sep 17 00:00:00 2001 From: Michael Stapelberg Date: Tue, 21 Jul 2009 19:07:30 +0200 Subject: Use own files for each function, add get_ipv6_addr.c --- src/get_ip_addr.c | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/get_ip_addr.c (limited to 'src/get_ip_addr.c') diff --git a/src/get_ip_addr.c b/src/get_ip_addr.c new file mode 100644 index 0000000..de03d8c --- /dev/null +++ b/src/get_ip_addr.c @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#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]; + struct ifreq ifr; + socklen_t len = sizeof(struct sockaddr_in); + memset(part, 0, sizeof(part)); + + /* First check if the interface is running */ + (void)strcpy(ifr.ifr_name, interface); + if (ioctl(general_socket, SIOCGIFFLAGS, &ifr) < 0 || + !(ifr.ifr_flags & IFF_RUNNING)) + return NULL; + + /* Interface is up, get the IP address */ + (void)strcpy(ifr.ifr_name, interface); + ifr.ifr_addr.sa_family = AF_INET; + if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0) + return "no IP"; + + int ret; + if ((ret = getnameinfo(&ifr.ifr_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) { + fprintf(stderr, "getnameinfo(): %s\n", gai_strerror(ret)); + return "no IP"; + } + + return part; +} + -- cgit v1.2.3