ip.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* See LICENSE file for copyright and license details. */
  2. #include <err.h>
  3. #include <netdb.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <ifaddrs.h>
  7. #if defined(__OpenBSD__)
  8. # include <sys/types.h>
  9. # include <sys/socket.h>
  10. #elif defined(__FreeBSD__)
  11. # include <netinet/in.h>
  12. # include <sys/socket.h>
  13. #endif
  14. #include "../lib/util.h"
  15. static inline void
  16. ip(char *out, const char *interface, sa_family_t sa_family)
  17. {
  18. int s;
  19. struct ifaddrs *ifa, *ifaddr;
  20. char host[NI_MAXHOST];
  21. if (getifaddrs(&ifaddr) < 0) {
  22. warn("getifaddrs");
  23. ERRRET(out);
  24. }
  25. for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
  26. if (!ifa->ifa_addr) { continue; }
  27. s = getnameinfo(ifa->ifa_addr,
  28. sizeof(struct sockaddr_in6),
  29. host,
  30. NI_MAXHOST,
  31. NULL,
  32. 0,
  33. NI_NUMERICHOST);
  34. if (!strcmp(ifa->ifa_name, interface)
  35. && (ifa->ifa_addr->sa_family == sa_family)) {
  36. freeifaddrs(ifaddr);
  37. if (s != 0) {
  38. warnx("getnameinfo: %s", gai_strerror(s));
  39. ERRRET(out);
  40. }
  41. bprintf(out, "%s", host);
  42. return;
  43. }
  44. }
  45. freeifaddrs(ifaddr);
  46. ERRRET(out);
  47. }
  48. void
  49. ipv4(char *out, const char *interface, uint32_t __unused _i, void __unused *_p)
  50. {
  51. ip(out, interface, AF_INET);
  52. }
  53. void
  54. ipv6(char *out, const char *interface, uint32_t __unused _i, void __unused *_p)
  55. {
  56. ip(out, interface, AF_INET6);
  57. }