inet_address.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #ifndef _IPYML_INET_ADDRESS_H
  2. #define _IPYML_INET_ADDRESS_H
  3. #include "yaml.h"
  4. #include <arpa/inet.h> // inet_ntop, socklen_t
  5. #include <bits/socket.h> // AF_*, socklen_t
  6. #include <cassert> // assert
  7. #include <cstring> // memcpy
  8. #include <libmnl/libmnl.h> // mnl_attr_*
  9. #include <linux/in.h> // struct in_addr_t
  10. #include <linux/netlink.h> // struct nlattr
  11. #include <netinet/in.h> // INET_ADDRSTRLEN
  12. #include <ostream> // std::ostream
  13. /*
  14. class may not have any virtual member due to:
  15. > error: union member ‘Address::<anonymous union>::inet_addr’
  16. > with non-trivial ‘constexpr InetAddress::InetAddress(InetAddress&&)’
  17. */
  18. class InetAddress { // : public YamlObject {
  19. unsigned char bytes[sizeof(in_addr_t)];
  20. public:
  21. InetAddress &operator=(const nlattr *attr) {
  22. assert(mnl_attr_validate(attr, MNL_TYPE_BINARY) == 0);
  23. assert(mnl_attr_get_payload_len(attr) == sizeof(bytes));
  24. memcpy(this->bytes, mnl_attr_get_payload(attr), sizeof(bytes));
  25. return *this;
  26. }
  27. void format(char *dst, socklen_t size) const {
  28. inet_ntop(AF_INET, bytes, dst, size);
  29. }
  30. void write_yaml(std::ostream &stream,
  31. const yaml_indent_level_t indent_level = 0) const {
  32. char str[INET_ADDRSTRLEN];
  33. format(str, sizeof(str));
  34. stream << str << '\n';
  35. }
  36. };
  37. #endif