if_indextoname.c 509 B

1234567891011121314151617181920212223
  1. #define _GNU_SOURCE
  2. #include <net/if.h>
  3. #include <sys/socket.h>
  4. #include <sys/ioctl.h>
  5. #include <string.h>
  6. #include <errno.h>
  7. #include "syscall.h"
  8. char *if_indextoname(unsigned index, char *name)
  9. {
  10. struct ifreq ifr;
  11. int fd, r;
  12. if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) return 0;
  13. ifr.ifr_ifindex = index;
  14. r = ioctl(fd, SIOCGIFNAME, &ifr);
  15. __syscall(SYS_close, fd);
  16. if (r < 0) {
  17. if (errno == ENODEV) errno = ENXIO;
  18. return 0;
  19. }
  20. return strncpy(name, ifr.ifr_name, IF_NAMESIZE);
  21. }