inet_address.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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/netlink.h> // struct nlattr
  10. #include <netinet/in.h> // INET_ADDRSTRLEN, struct in_addr
  11. #include <ostream> // std::ostream
  12. /*
  13. class may not have any virtual member due to:
  14. > error: union member ‘Address::<anonymous union>::inet_addr’
  15. > with non-trivial ‘constexpr InetAddress::InetAddress(InetAddress&&)’
  16. */
  17. class InetAddress { // : public YamlObject {
  18. unsigned char bytes[sizeof(in_addr)];
  19. public:
  20. InetAddress &operator=(const nlattr *attr) {
  21. assert(mnl_attr_validate(attr, MNL_TYPE_BINARY) == 0);
  22. assert(mnl_attr_get_payload_len(attr) == sizeof(bytes));
  23. memcpy(this->bytes, mnl_attr_get_payload(attr), sizeof(bytes));
  24. return *this;
  25. }
  26. void format(char *dst, socklen_t size) const {
  27. inet_ntop(AF_INET, bytes, dst, size);
  28. }
  29. void write_yaml(std::ostream &stream,
  30. const yaml_indent_level_t indent_level = 0) const {
  31. char str[INET_ADDRSTRLEN];
  32. format(str, sizeof(str));
  33. stream << str << '\n';
  34. }
  35. };
  36. #endif