Browse Source

new class InetAddress

Fabian Peter Hammerle 7 years ago
parent
commit
f964b77668
2 changed files with 41 additions and 12 deletions
  1. 4 12
      address.h
  2. 37 0
      inet_address.h

+ 4 - 12
address.h

@@ -1,20 +1,16 @@
 #ifndef _IPYML_ADDRESS_H
 #define _IPYML_ADDRESS_H
 
+#include "inet_address.h"
 #include "yaml.h"
 
-#include <arpa/inet.h>
-#include <cassert>
-#include <cstring>
 #include <libmnl/libmnl.h>
 #include <linux/if_addr.h>
 #include <linux/netlink.h>
-#include <netinet/in.h>
 #include <ostream>
 
 class Address : public YamlObject {
-public:
-  unsigned char address[sizeof(in_addr_t)];
+  InetAddress inet_addr;
 
 public:
   // typedef int (*mnl_attr_cb_t)(const struct nlattr *attr, void *data);
@@ -23,9 +19,7 @@ public:
     // /usr/include/linux/if_addr.h
     switch (mnl_attr_get_type(attr)) {
     case IFA_ADDRESS:
-      assert(mnl_attr_validate(attr, MNL_TYPE_BINARY) == 0);
-      assert(mnl_attr_get_payload_len(attr) == sizeof(address));
-      memcpy(addr->address, mnl_attr_get_payload(attr), sizeof(address));
+      addr->inet_addr = attr;
       break;
     }
   }
@@ -33,9 +27,7 @@ public:
   void write_yaml(std::ostream &stream,
                   const yaml_indent_level_t indent_level = 0) const {
     // const std::string indent(indent_level, ' ');
-    char addr_str[INET_ADDRSTRLEN];
-    inet_ntop(AF_INET, address, addr_str, sizeof(addr_str));
-    stream << addr_str << '\n';
+    inet_addr.write_yaml(stream, indent_level + 2);
   }
 };
 

+ 37 - 0
inet_address.h

@@ -0,0 +1,37 @@
+#ifndef _IPYML_INET_ADDRESS_H
+#define _IPYML_INET_ADDRESS_H
+
+#include "yaml.h"
+
+#include <arpa/inet.h>
+#include <cassert>
+#include <cstring>
+#include <libmnl/libmnl.h>
+#include <linux/netlink.h>
+#include <netinet/in.h>
+#include <ostream>
+
+class InetAddress : public YamlObject {
+  unsigned char bytes[sizeof(in_addr_t)];
+
+public:
+  InetAddress &operator=(const nlattr *attr) {
+    assert(mnl_attr_validate(attr, MNL_TYPE_BINARY) == 0);
+    assert(mnl_attr_get_payload_len(attr) == sizeof(bytes));
+    memcpy(this->bytes, mnl_attr_get_payload(attr), sizeof(bytes));
+    return *this;
+  }
+
+  void format(char *dst, socklen_t size) const {
+    inet_ntop(AF_INET, bytes, dst, size);
+  }
+
+  void write_yaml(std::ostream &stream,
+                  const yaml_indent_level_t indent_level = 0) const {
+    char str[INET_ADDRSTRLEN];
+    format(str, sizeof(str));
+    stream << str << '\n';
+  }
+};
+
+#endif