#include <iostream> #include <Windows.h> #include <netfw.h> int main() { HRESULT hr = CoInitializeEx(0, COINIT_APARTMENTTHREADED);// 初始化 COM if (SUCCEEDED(hr)) { INetFwPolicy2* pFwPolicy2 = NULL; //创建防火墙策略 hr = CoCreateInstance(__uuidof(NetFwPolicy2), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwPolicy2), (void**)&pFwPolicy2); if (SUCCEEDED(hr)) { INetFwRules* pFwRules = NULL; //获取防火墙规则 hr = pFwPolicy2->get_Rules(&pFwRules); if (SUCCEEDED(hr)) { INetFwRule* pFwRule = NULL; // 在这里你可以通过遍历 pFwRules 获取并修改你想要的规则 // 例如,假设我们要修改名为 "MyFirewallRule" 的规则 BSTR ruleName = SysAllocString(L"MyFirewallRule"); //从规则集合中获取指定名称的规则 hr = pFwRules->Item(ruleName, &pFwRule); if (SUCCEEDED(hr)) { std::cout << "Firewall rule is exist" << std::endl; pFwRules->Remove(ruleName);//删除名为""MyFirewallRule"的防火墙 SysFreeString(ruleName); pFwRules->Release(); pFwPolicy2->Release();
CoUninitialize();//反初始化COM return -1; } //创建一个新的防火墙规则 hr = CoCreateInstance(__uuidof(NetFwRule), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwRule),(void**)&pFwRule); if (SUCCEEDED(hr)) { // 设置规则的属性 pFwRule->put_Name(ruleName); pFwRule->put_Description(SysAllocString(L"My Firewall Rule")); pFwRule->put_Action(NET_FW_ACTION_ALLOW); // 允许连接 pFwRule->put_Direction(NET_FW_RULE_DIR_IN); // 入站规则 pFwRule->put_Enabled(VARIANT_TRUE); // 启用规则 pFwRule->put_Protocol(NET_FW_IP_PROTOCOL_TCP); // TCP 协议 pFwRule->put_LocalPorts(SysAllocString(L"83")); // 本地端口 83 pFwRule->put_InterfaceTypes(SysAllocString(L"All")); // 适用于所有网络接口 // 将规则添加到规则集合中 hr = pFwRules->Add(pFwRule); if (SUCCEEDED(hr)) { std::cout << "Firewall rule added successfully." << std::endl; } else { std::cout << "Failed to add firewall rule: " << hr << std::endl; } pFwRule->Release(); } SysFreeString(ruleName); pFwRules->Release(); } pFwPolicy2->Release(); } CoUninitialize();//反初始化COM } return 0; }
创建防火墙之前:
创建防火墙之后:
标签:Windows,pFwRule,防火墙,C++,hr,规则,put,pFwRules From: https://www.cnblogs.com/TechNomad/p/17649345.html