dump_interfaces_netbsd.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include "diagnostic/dump_interfaces.hpp"
  2. #include <ifaddrs.h>
  3. #include <net/if.h>
  4. #include <sys/ioctl.h>
  5. #include <net/if_dl.h>
  6. #include <netinet/in.h>
  7. #include <arpa/inet.h>
  8. #include <unistd.h>
  9. #include <cstring>
  10. #include <sstream>
  11. void dumpInterfaces(std::stringstream& dump) {
  12. struct ifaddrs *ifap, *ifa;
  13. if (getifaddrs(&ifap) != 0) {
  14. dump << "ERROR: getifaddrs failed\n";
  15. return;
  16. }
  17. for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
  18. if (!ifa->ifa_addr) continue;
  19. dump << "Interface: " << ifa->ifa_name << "\n";
  20. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  21. if (sock >= 0) {
  22. struct ifreq ifr;
  23. strncpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ);
  24. if (ioctl(sock, SIOCGIFMTU, &ifr) == 0) {
  25. dump << "MTU: " << ifr.ifr_mtu << "\n";
  26. }
  27. if (ifa->ifa_addr->sa_family == AF_LINK) {
  28. struct sockaddr_dl* sdl = (struct sockaddr_dl*)ifa->ifa_addr;
  29. unsigned char* mac = (unsigned char*)LLADDR(sdl);
  30. char macStr[32];
  31. snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
  32. mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  33. dump << "MAC: " << macStr << "\n";
  34. }
  35. close(sock);
  36. }
  37. dump << "Addresses:\n";
  38. if (ifa->ifa_addr->sa_family == AF_INET) {
  39. char addr[INET_ADDRSTRLEN];
  40. struct sockaddr_in* sa = (struct sockaddr_in*)ifa->ifa_addr;
  41. inet_ntop(AF_INET, &(sa->sin_addr), addr, INET_ADDRSTRLEN);
  42. dump << addr << "\n";
  43. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  44. char addr[INET6_ADDRSTRLEN];
  45. struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ifa->ifa_addr;
  46. inet_ntop(AF_INET6, &(sa6->sin6_addr), addr, INET6_ADDRSTRLEN);
  47. dump << addr << "\n";
  48. }
  49. dump << "\n";
  50. }
  51. freeifaddrs(ifap);
  52. }