node_state_interfaces_netbsd.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "diagnostic/node_state_interfaces_netbsd.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 <vector>
  11. void addNodeStateInterfacesJson(nlohmann::json& j) {
  12. try {
  13. std::vector<nlohmann::json> interfaces_json;
  14. struct ifaddrs *ifap, *ifa;
  15. if (getifaddrs(&ifap) != 0) {
  16. j["network_interfaces"] = "ERROR: getifaddrs failed";
  17. return;
  18. }
  19. for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
  20. if (!ifa->ifa_addr) continue;
  21. nlohmann::json iface_json;
  22. iface_json["name"] = ifa->ifa_name;
  23. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  24. if (sock >= 0) {
  25. struct ifreq ifr;
  26. strncpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ);
  27. if (ioctl(sock, SIOCGIFMTU, &ifr) == 0) {
  28. iface_json["mtu"] = ifr.ifr_mtu;
  29. }
  30. if (ifa->ifa_addr->sa_family == AF_LINK) {
  31. struct sockaddr_dl* sdl = (struct sockaddr_dl*)ifa->ifa_addr;
  32. unsigned char* mac = (unsigned char*)LLADDR(sdl);
  33. char macStr[32];
  34. snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
  35. mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  36. iface_json["mac"] = macStr;
  37. }
  38. close(sock);
  39. }
  40. std::vector<std::string> addresses;
  41. if (ifa->ifa_addr->sa_family == AF_INET) {
  42. char addr[INET_ADDRSTRLEN];
  43. struct sockaddr_in* sa = (struct sockaddr_in*)ifa->ifa_addr;
  44. inet_ntop(AF_INET, &(sa->sin_addr), addr, INET_ADDRSTRLEN);
  45. addresses.push_back(addr);
  46. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  47. char addr[INET6_ADDRSTRLEN];
  48. struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ifa->ifa_addr;
  49. inet_ntop(AF_INET6, &(sa6->sin6_addr), addr, INET6_ADDRSTRLEN);
  50. addresses.push_back(addr);
  51. }
  52. iface_json["addresses"] = addresses;
  53. interfaces_json.push_back(iface_json);
  54. }
  55. freeifaddrs(ifap);
  56. j["network_interfaces"] = interfaces_json;
  57. } catch (const std::exception& e) {
  58. j["network_interfaces"] = std::string("Exception: ") + e.what();
  59. } catch (...) {
  60. j["network_interfaces"] = "Unknown error retrieving interfaces";
  61. }
  62. }