if_nametoindex.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* include if_nametoindex */
  2. #include "unpifi.h"
  3. #include "unproute.h"
  4. unsigned int
  5. if_nametoindex(const char *name)
  6. {
  7. unsigned int idx, namelen;
  8. char *buf, *next, *lim;
  9. size_t len;
  10. struct if_msghdr *ifm;
  11. struct sockaddr *sa, *rti_info[RTAX_MAX];
  12. struct sockaddr_dl *sdl;
  13. if ( (buf = net_rt_iflist(0, 0, &len)) == NULL)
  14. return(0);
  15. namelen = strlen(name);
  16. lim = buf + len;
  17. for (next = buf; next < lim; next += ifm->ifm_msglen) {
  18. ifm = (struct if_msghdr *) next;
  19. if (ifm->ifm_type == RTM_IFINFO) {
  20. sa = (struct sockaddr *) (ifm + 1);
  21. get_rtaddrs(ifm->ifm_addrs, sa, rti_info);
  22. if ( (sa = rti_info[RTAX_IFP]) != NULL) {
  23. if (sa->sa_family == AF_LINK) {
  24. sdl = (struct sockaddr_dl *) sa;
  25. if (sdl->sdl_nlen == namelen && strncmp(&sdl->sdl_data[0], name, sdl->sdl_nlen) == 0) {
  26. idx = sdl->sdl_index; /* save before free() */
  27. free(buf);
  28. return(idx);
  29. }
  30. }
  31. }
  32. }
  33. }
  34. free(buf);
  35. return(0); /* no match for name */
  36. }
  37. /* end if_nametoindex */
  38. unsigned int
  39. If_nametoindex(const char *name)
  40. {
  41. int idx;
  42. if ( (idx = if_nametoindex(name)) == 0)
  43. err_quit("if_nametoindex error for %s", name);
  44. return(idx);
  45. }