util: enhance MAC address parsing
Current ether_aton does not support the MAC string without colons.
Add extra conversion when string length equal to 12.
Test log:
1/7 config_parser OK 0.01s
2/7 neighbor OK 0.01s
3/7 netlink OK 0.01s
4/7 util OK 0.01s
5/7 network_manager OK 0.01s
6/7 ethernet_interface OK 0.01s
7/7 vlan_interface OK 0.01s
Ok: 7
Expected Fail: 0
Fail: 0
Unexpected Pass: 0
Skipped: 0
Timeout: 0
Signed-off-by: Potin Lai <potin.lai@quantatw.com>
Change-Id: Id2125af85f1c3d75424ff6ea0980c1460614f14e
Signed-off-by: Patrick Williams <patrick@stwcx.xyz>
diff --git a/src/util.cpp b/src/util.cpp
index 5c5e427..094e4bf 100644
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -633,14 +633,31 @@
return fromString(std::get<std::string>(value));
}
-ether_addr fromString(const char* str)
+ether_addr fromString(std::string_view str)
{
- struct ether_addr* mac = ether_aton(str);
- if (mac == nullptr)
+ std::string mac_str{};
+ ether_addr mac{};
+
+ auto mac_c_str = str.data();
+
+ // MAC address without colons
+ if (str.size() == 12 && str.find(":") == std::string::npos)
{
- throw std::invalid_argument("Invalid MAC Address");
+ mac_str = std::string(str.substr(0, 2)) + ":" +
+ std::string(str.substr(2, 2)) + ":" +
+ std::string(str.substr(4, 2)) + ":" +
+ std::string(str.substr(6, 2)) + ":" +
+ std::string(str.substr(8, 2)) + ":" +
+ std::string(str.substr(10, 2));
+ mac_c_str = mac_str.c_str();
}
- return *mac;
+
+ if (ether_aton_r(mac_c_str, &mac) != nullptr)
+ {
+ return mac;
+ }
+
+ throw std::invalid_argument("Invalid MAC Address");
}
std::string toString(const ether_addr& mac)
diff --git a/src/util.hpp b/src/util.hpp
index 804d492..b1d27c4 100644
--- a/src/util.hpp
+++ b/src/util.hpp
@@ -44,11 +44,7 @@
* @returns A mac address in network byte order
* @throws std::runtime_error for bad mac
*/
-ether_addr fromString(const char* str);
-inline ether_addr fromString(const std::string& str)
-{
- return fromString(str.c_str());
-}
+ether_addr fromString(std::string_view str);
/** @brief Converts the given mac address bytes into a string
* @param[in] mac - The mac address