diff --git a/src/linux/get_macaddr.cpp b/src/linux/get_macaddr.cpp index 63c2589341c0fcf5e3a31bd130c952f4d2b1a6d5..c7807e9158f740def17c5a24edae85081a17d918 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; }