批量设置默认网关和DNS
环境:VS2022
配置:使用Release版本输出的exe,否则在使用时会提示少dll
代码:
#ifndef CMDEXC_H #define CMDEXC_H #include <cstring> #include<cstdio> #include<iostream> #include <regex> #include <iostream> using namespace std; class CmdExc { public: CmdExc(std::string cmd, std::string mode = "rt"); virtual ~CmdExc(); std::string getOutput() const; private: std::string m_strOutput__; FILE* m_fp__; }; CmdExc::CmdExc(std::string cmd, std::string mode) { m_fp__ = _popen(cmd.c_str(), mode.c_str()); char buf[256] = { 0 }; if (NULL != m_fp__) { int read_len; while ((read_len = fread(buf, sizeof(buf) - 1, 1, m_fp__)) > 0) { m_strOutput__ += buf; memset(buf, 0, sizeof(buf)); } } } CmdExc::~CmdExc() { if (NULL != m_fp__) { _pclose(m_fp__); } } std::string CmdExc::getOutput() const { return m_strOutput__; } #endif // CMDEXC_H std::string extractIP(const std::string& text) { std::regex ipRegex("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})"); std::smatch match; if (std::regex_search(text, match, ipRegex)) { return match.str(); } else { return "No IP found"; } } int main() { printf("正在设置默认网关和DNS....\n"); CmdExc cmd("ipconfig"); string text = cmd.getOutput().c_str(); string ip = extractIP(text); string command = "netsh interface ip set address \"以太网 3\" source=static address=" + ip+" 255.255.224.0 gateway=192.168.0.2"; system(command.c_str()); command = "netsh interface ip set dnsservers \"以太网 3\" static 223.5.5.5 primary no"; system(command.c_str()); printf("设置成功\n"); system("pause"); }