在Linux系统中,你可以使用ip
命令或ifconfig
命令来获取网关信息
方法1:使用ip
命令
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
std::string get_gateway() {
std::string gateway;
std::string line;
std::istringstream iss("/proc/net/route");
while (std::getline(iss, line)) {
std::vector<std::string> tokens;
std::stringstream ss(line);
std::string token;
while (std::getline(ss, token, ' ')) {
tokens.push_back(token);
}
if (tokens[0] == "default" && tokens[3] != "0.0.0.0") {
gateway = tokens[2];
break;
}
}
return gateway;
}
int main() {
std::string gateway = get_gateway();
std::cout << "Gateway: " << gateway << std::endl;
return 0;
}
方法2:使用ifconfig
命令
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>
std::string get_gateway() {
std::string gateway;
std::string line;
std::istringstream iss((std::system("ifconfig") + "\n").c_str());
while (std::getline(iss, line)) {
std::vector<std::string> tokens;
std::stringstream ss(line);
std::string token;
while (std::getline(ss, token, ' ')) {
tokens.push_back(token);
}
if (tokens[0] == "default" && tokens[3] != "0.0.0.0") {
gateway = tokens[2];
break;
}
}
return gateway;
}
int main() {
std::string gateway = get_gateway();
std::cout << "Gateway: " << gateway << std::endl;
return 0;
}
这两种方法都可以帮助你获取Linux系统中的网关信息。请注意,这些方法可能需要root权限才能正常运行。