summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Herrmann <dh.herrmann@gmail.com>2013-11-04 12:02:40 +0100
committerDavid Herrmann <dh.herrmann@gmail.com>2013-11-04 12:02:40 +0100
commitad20d9868ed348235d96a59ec1a51494b3aac3d7 (patch)
treed5018605a62ce6f067df194200478019bfdf0da9
parenta03e95ff50e9d63f7415c5f67c1b51d250a51ca7 (diff)
owfd: shared: add if_name_to_index helper
gdhcp requires an interface index instead of an interface name. This helpers returns the index of an interface or an error if the interface cannot be found. Signed-off-by: David Herrmann <dh.herrmann@gmail.com>
-rw-r--r--src/shared.c30
-rw-r--r--src/shared.h1
2 files changed, 31 insertions, 0 deletions
diff --git a/src/shared.c b/src/shared.c
index 3522144..da3f3d1 100644
--- a/src/shared.c
+++ b/src/shared.c
@@ -25,11 +25,16 @@
#include <errno.h>
#include <fcntl.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <netinet/udp.h>
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include "shared.h"
@@ -51,3 +56,28 @@ void us_to_timespec(struct timespec *ts, int64_t us)
ts->tv_sec = us / (1000LL * 1000LL);
ts->tv_nsec = (us % (1000LL * 1000LL)) * 1000LL;
}
+
+int if_name_to_index(const char *name)
+{
+ struct ifreq ifr;
+ int fd, r;
+
+ if (strlen(name) > sizeof(ifr.ifr_name))
+ return -EINVAL;
+
+ fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return -errno;
+
+ memset(&ifr, 0, sizeof(ifr));
+ strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+
+ r = ioctl(fd, SIOCGIFINDEX, &ifr);
+ if (r < 0)
+ r = -errno;
+ else
+ r = ifr.ifr_ifindex;
+
+ close(fd);
+ return r;
+}
diff --git a/src/shared.h b/src/shared.h
index 42b1367..d1ef39f 100644
--- a/src/shared.h
+++ b/src/shared.h
@@ -36,6 +36,7 @@ extern "C" {
int64_t get_time_us(void);
void us_to_timespec(struct timespec *ts, int64_t us);
+int if_name_to_index(const char *name);
#ifdef __cplusplus
}