From b0b02150f2fcd3d84169c7a974526aeec55e27b2 Mon Sep 17 00:00:00 2001 From: Felipe Shi Iu Wu <felipeshiwu@gmail.com> Date: Tue, 25 Oct 2016 11:27:08 -0200 Subject: [PATCH] Issue #15: Check all possible names for the network interface Signed-off-by: Felipe Shi Iu Wu <felipeshiwu@gmail.com> --- src/linux/get_macaddr.cpp | 41 +++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/src/linux/get_macaddr.cpp b/src/linux/get_macaddr.cpp index 63c25893..c7807e91 100644 --- a/src/linux/get_macaddr.cpp +++ b/src/linux/get_macaddr.cpp @@ -25,17 +25,42 @@ std::string get_macaddr() { std::fstream file; std::string macaddr; - file.open("/sys/class/net/eth0/address", std::ifstream::in); + /* #FIXME The way we are breaking the getline to get the network + * interface is not very efficient, because we create a char + * array and a string to the same thing. + */ - if (!file.is_open()) { - file.open("/sys/class/net/eth1/address", std::ifstream::in); - if (!file.is_open()) { - throw std::string("No address file found."); + char line[40]; + char iface[20]; + char dest[20]; + std::string Iface; + std::string Destination; + std::string file_path; + + FILE *fp = fopen("/proc/net/route", "r"); + fgets (line, sizeof(line), fp); // Skip the first line (column headers). + + /* Loop to found the default network interface*/ + while (fgets(line, sizeof(line), fp)) { + + /* Found the interface name and check that it is default*/ + sscanf(line, "%s %s\n", iface, dest); + + Iface = iface; + Destination = dest; + + if (Destination == "00000000") { // found default network interface + /* found macaddr with the default network interface*/ + file_path = "/sys/class/net/"+Iface+"/address"; + file.open(file_path, std::ifstream::in); + if (!file.is_open()) { + throw std::string("No address file found."); + } + getline(file, macaddr); // get macaddr + file.close(); } } - - getline(file, macaddr); - file.close(); + fclose(fp); return macaddr; } -- GitLab