Implement fetching hardware address
Bug: 159327274
Test: manual
Change-Id: Ic3c7d757141da498f7d86ffabadac21a2372f443
diff --git a/automotive/can/1.0/default/libnetdevice/include/libnetdevice/libnetdevice.h b/automotive/can/1.0/default/libnetdevice/include/libnetdevice/libnetdevice.h
index 54cbafc..c8e6f75 100644
--- a/automotive/can/1.0/default/libnetdevice/include/libnetdevice/libnetdevice.h
+++ b/automotive/can/1.0/default/libnetdevice/include/libnetdevice/libnetdevice.h
@@ -16,11 +16,16 @@
#pragma once
+#include <linux/if_ether.h>
+
+#include <array>
#include <optional>
#include <string>
namespace android::netdevice {
+typedef std::array<uint8_t, ETH_ALEN> hwaddr_t;
+
/**
* Configures libnetdevice to use PF_CAN sockets instead of AF_INET,
* what requires less permissive SEPolicy rules for a given process.
@@ -91,4 +96,14 @@
*/
bool del(std::string dev);
+/**
+ * Fetches interface's hardware address.
+ *
+ * \param ifname Interface name
+ * \return Hardware address (MAC address) or nullopt if the lookup failed
+ */
+std::optional<hwaddr_t> getHwAddr(const std::string& ifname);
+
} // namespace android::netdevice
+
+bool operator==(const android::netdevice::hwaddr_t lhs, const unsigned char rhs[ETH_ALEN]);
diff --git a/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp b/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp
index 73b91d0..a16dd34 100644
--- a/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp
+++ b/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp
@@ -81,4 +81,18 @@
return sock.send(req) && sock.receiveAck();
}
+std::optional<hwaddr_t> getHwAddr(const std::string& ifname) {
+ auto ifr = ifreqs::fromName(ifname);
+ if (!ifreqs::send(SIOCGIFHWADDR, ifr)) return std::nullopt;
+
+ hwaddr_t hwaddr;
+ memcpy(hwaddr.data(), ifr.ifr_hwaddr.sa_data, hwaddr.size());
+ return hwaddr;
+}
+
} // namespace android::netdevice
+
+bool operator==(const android::netdevice::hwaddr_t lhs, const unsigned char rhs[ETH_ALEN]) {
+ static_assert(lhs.size() == ETH_ALEN);
+ return 0 == memcmp(lhs.data(), rhs, lhs.size());
+}