#ifndef DISTRIBUTION_SERVICE_NETWORK_H #define DISTRIBUTION_SERVICE_NETWORK_H #include "CCString.h" #include "Socket/CCSocket.h" #ifdef _WIN32 #elif __linux__ #include #endif class NetWorkInfo { public: static CTL::String getGw() { #ifdef _WIN32 // Windows实现 return CTL::String(""); #elif __linux__ // Linux实现:从/proc/net/route读取默认网关 std::ifstream routeFile("/proc/net/route"); std::string line; // 跳过标题行 std::getline(routeFile, line); while (std::getline(routeFile, line)) { std::istringstream iss(line); std::string iface, dest, gateway; if (iss >> iface >> dest >> gateway) { // 查找默认路由(目标地址为00000000) if (dest == "00000000" && gateway != "00000000") { // 将十六进制网关地址转换为点分十进制格式 unsigned int gw; std::stringstream ss; ss << std::hex << gateway; ss >> gw; // 注意字节序转换 gw = (gw & 0xFF) << 24 | ((gw >> 8) & 0xFF) << 16 | ((gw >> 16) & 0xFF) << 8 | (gw >> 24) & 0xFF; in_addr addr; addr.s_addr = htonl(gw); return CTL::String(inet_ntoa(addr)); } } } return CTL::String(""); #endif } // 获取网关 static CTL::String getNm() { #ifdef _WIN32 // Windows实现 return CTL::String(""); #elif __linux__ // Linux实现:尝试从常见网络接口获取子网掩码 const char* interfaces[] = {"eth0", "wlan0", "enp0s3", "ens33","enp4s0"}; int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { return CTL::String(""); } for (int i = 0; i < 5; i++) { struct ifreq ifr{}; strncpy(ifr.ifr_name, interfaces[i], IFNAMSIZ - 1); // 获取子网掩码 if (ioctl(sock, SIOCGIFNETMASK, &ifr) == 0) { struct sockaddr_in* netmask = reinterpret_cast(&ifr.ifr_netmask); close(sock); return CTL::String(inet_ntoa(netmask->sin_addr)); } } close(sock); return CTL::String(""); #endif } // 获取子网掩码 }; #endif