implement if_indextoname and if_nametoindex functions
authorRich Felker <dalias@aerifal.cx>
Tue, 5 Apr 2011 17:20:08 +0000 (13:20 -0400)
committerRich Felker <dalias@aerifal.cx>
Tue, 5 Apr 2011 17:20:08 +0000 (13:20 -0400)
src/network/if_indextoname.c [new file with mode: 0644]
src/network/if_nametoindex.c [new file with mode: 0644]

diff --git a/src/network/if_indextoname.c b/src/network/if_indextoname.c
new file mode 100644 (file)
index 0000000..f18f17a
--- /dev/null
@@ -0,0 +1,18 @@
+#define _GNU_SOURCE
+#include <net/if.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <string.h>
+#include "syscall.h"
+
+char *if_indextoname(unsigned index, char *name)
+{
+       struct ifreq ifr;
+       int fd, r;
+
+       if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) return 0;
+       ifr.ifr_ifindex = index;
+       r = ioctl(fd, SIOCGIFNAME, &ifr);
+       __syscall(SYS_close, fd);
+       return r < 0 ? 0 : strncpy(name, ifr.ifr_name, IF_NAMESIZE);
+}
diff --git a/src/network/if_nametoindex.c b/src/network/if_nametoindex.c
new file mode 100644 (file)
index 0000000..419931f
--- /dev/null
@@ -0,0 +1,18 @@
+#define _GNU_SOURCE
+#include <net/if.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <string.h>
+#include "syscall.h"
+
+unsigned if_nametoindex(const char *name)
+{
+       struct ifreq ifr;
+       int fd, r;
+
+       if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) return -1;
+       strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
+       r = ioctl(fd, SIOCGIFINDEX, &ifr);
+       __syscall(SYS_close, fd);
+       return r < 0 ? r : ifr.ifr_ifindex;
+}