address.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #ifndef _IPYML_ADDRESS_H
  2. #define _IPYML_ADDRESS_H
  3. #include "yaml.h"
  4. #include <arpa/inet.h>
  5. #include <cassert>
  6. #include <cstring>
  7. #include <libmnl/libmnl.h>
  8. #include <linux/if_addr.h>
  9. #include <linux/netlink.h>
  10. #include <netinet/in.h>
  11. #include <ostream>
  12. class Address : public YamlObject {
  13. public:
  14. unsigned char address[sizeof(in_addr_t)];
  15. public:
  16. // typedef int (*mnl_attr_cb_t)(const struct nlattr *attr, void *data);
  17. static int mnl_attr_cb(const nlattr *attr, void *data) {
  18. Address *addr = (Address *)data;
  19. // /usr/include/linux/if_addr.h
  20. switch (mnl_attr_get_type(attr)) {
  21. case IFA_ADDRESS:
  22. assert(mnl_attr_validate(attr, MNL_TYPE_BINARY) == 0);
  23. assert(mnl_attr_get_payload_len(attr) == sizeof(address));
  24. memcpy(addr->address, mnl_attr_get_payload(attr), sizeof(address));
  25. break;
  26. }
  27. }
  28. void write_yaml(std::ostream &stream,
  29. const yaml_indent_level_t indent_level = 0) const {
  30. // const std::string indent(indent_level, ' ');
  31. char addr_str[INET_ADDRSTRLEN];
  32. inet_ntop(AF_INET, address, addr_str, sizeof(addr_str));
  33. stream << addr_str << '\n';
  34. }
  35. };
  36. #endif