hardware_address.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #ifndef _IPYML_HARDWARE_ADDRESS_H
  2. #define _IPYML_HARDWARE_ADDRESS_H
  3. #include "yaml.h"
  4. #include <cassert>
  5. #include <cstring>
  6. #include <iomanip>
  7. #include <libmnl/libmnl.h>
  8. #include <linux/if.h>
  9. #include <linux/netlink.h>
  10. #include <ostream>
  11. #include <sstream>
  12. #include <string>
  13. class HardwareAddress : public YamlObject {
  14. uint8_t bytes[IFHWADDRLEN];
  15. public:
  16. HardwareAddress &operator=(const nlattr *attr) {
  17. assert(mnl_attr_validate(attr, MNL_TYPE_BINARY) == 0);
  18. assert(mnl_attr_get_payload_len(attr) == IFHWADDRLEN);
  19. memcpy(this->bytes, mnl_attr_get_payload(attr), IFHWADDRLEN);
  20. return *this;
  21. }
  22. bool specified() const {
  23. for (unsigned char i = 0; i < IFHWADDRLEN; i++) {
  24. if (bytes[i] != 0x00) {
  25. return true;
  26. }
  27. }
  28. return false;
  29. }
  30. std::string format() const {
  31. std::stringstream ss;
  32. ss << std::hex << std::setfill('0');
  33. for (int i = 0; i < IFHWADDRLEN; i++) {
  34. if (i != 0) {
  35. ss << ':';
  36. }
  37. ss << std::setw(2) << (int)bytes[i];
  38. }
  39. return ss.str();
  40. }
  41. void write_yaml(std::ostream &stream,
  42. const yaml_indent_level_t indent_level = 0) const {
  43. stream << format() << '\n';
  44. }
  45. };
  46. #endif