ip.c 1.2 KB

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