address.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #ifndef _IPYML_ADDRESS_H
  2. #define _IPYML_ADDRESS_H
  3. #include "inet6_address.h"
  4. #include "inet_address.h"
  5. #include "yaml.h"
  6. #include <bits/socket.h> // AF_*
  7. #include <libmnl/libmnl.h> // mnl_attr_get_type
  8. #include <linux/if_addr.h> // struct ifaddrmsg
  9. #include <linux/netlink.h> // struct nlattr
  10. #include <ostream> // std::ostream
  11. class Address : public YamlObject {
  12. public:
  13. unsigned int ifindex;
  14. private:
  15. unsigned char family;
  16. union {
  17. InetAddress inet_addr;
  18. Inet6Address inet6_addr;
  19. };
  20. public:
  21. Address(const ifaddrmsg *msg) {
  22. /*
  23. struct ifaddrmsg {
  24. unsigned char ifa_family; // Address type
  25. unsigned char ifa_prefixlen; // Prefixlength of address
  26. unsigned char ifa_flags; // Address flags
  27. unsigned char ifa_scope; // Address scope
  28. int ifa_index; // Interface index
  29. };
  30. */
  31. ifindex = msg->ifa_index;
  32. family = msg->ifa_family;
  33. assert(family == AF_INET || family == AF_INET6);
  34. }
  35. // typedef int (*mnl_attr_cb_t)(const struct nlattr *attr, void *data);
  36. static int mnl_attr_cb(const nlattr *attr, void *data) {
  37. Address *addr = (Address *)data;
  38. assert(addr->family != AF_UNSPEC);
  39. // /usr/include/linux/if_addr.h
  40. switch (mnl_attr_get_type(attr)) {
  41. case IFA_ADDRESS:
  42. if (addr->family == AF_INET) {
  43. addr->inet_addr = attr;
  44. } else if (addr->family == AF_INET6) {
  45. addr->inet6_addr = attr;
  46. }
  47. break;
  48. }
  49. }
  50. void write_yaml(std::ostream &stream,
  51. const yaml_indent_level_t indent_level = 0) const {
  52. // const std::string indent(indent_level, ' ');
  53. if (family == AF_INET) {
  54. inet_addr.write_yaml(stream, indent_level + 2);
  55. } else if (family == AF_INET6) {
  56. inet6_addr.write_yaml(stream, indent_level + 2);
  57. }
  58. }
  59. };
  60. #endif