我对C ++还是很陌生,我正在尝试创建一个实用程序,该实用程序可以找到所有网络设备并列出其名称和MAC地址。我已经编译了所有内容,但是当我运行to_string()
方法时,没有任何输出到终端。我相信我正在访问迭代器对象,并错误地对其调用to_string()
。
//networkinterfacelist_class.cpp
#include "networkinterfacelist.h"
//get list of network interfaces and push them into a vector list
networkinterfacelist_class::networkinterfacelist_class(){
if ((dir = opendir ("/sys/class/net")) != NULL){
while ((ent = readdir (dir)) != NULL) {
std::string device(ent->d_name);
//skips the parent and current folder
if(device == "." || device == ".."){
continue;
}
dir_list.push_back(device);
}
closedir (dir);
}
}
//iterate through the devices and find their mac addresses
std::vector<networkinterface_class> networkinterfacelist_class::create_device(){
for( std::vector<std::string>::iterator it = dir_list.begin(); it != dir_list.end(); ++it){
if ((dir2 = opendir ("/sys/class/net")) != NULL){
if ((dir = opendir (it->c_str())) != NULL){
//opens the address file saves mac address in line
inFile.open("address");
while(!inFile){
getline(inFile, line);
}
//creates a new networkinterface class and pushes it onto a list
networkinterface_class obj( *it , line);
list.push_back(obj);
}
}
}
return list;
}
//iterates over the list of network devices and prints their name and mac address
void networkinterfacelist_class::to_string(){
for(std::vector<networkinterface_class>::iterator it = list.begin(); it != list.end(); ++it){
(*it).to_string();
}
}
和我的networkinterface类
//networkinterface_class.cpp
#include "networkinterface.h"
networkinterface_class::networkinterface_class(std::string device, std::string macaddress){
name = device;
mac = macaddress;
}
std::string networkinterface_class::get_name(){
return name;
}
std::string networkinterface_class::get_mac(){
return mac;
}
void networkinterface_class::to_string(){
std::cout << "Name: " << networkinterface_class::get_name() << "\tMAC: " << networkinterface_class::get_mac() << std::endl;
}
任何帮助或提示将不胜感激
答案 0 :(得分:1)
您需要为设备定义整个路径。
dir_list.push_back(device); // it pushes only d_name of dirent == filename
在上面的行中,您仅推送/sys/class/net
中的设备名称,因此,当您要读取此设备时,需要通过将 / sys / class / net / 与设备名称
if ((dir = opendir ( ("/sys/class/net/" + *it).c_str() )) != NULL){
^^^ get device name as string
代替
if ((dir = opendir (it->c_str())) != NULL){ // you pass only device without full path
要打开address
文件时,请执行以下操作:
inFile.open("/sys/class/net/" + *it + "/address");
现在您可以阅读此文件的内容。