有时候在代码中我们需要检测防火墙的状态变化,就可以使用windows提供的API函数
#include <windows.h>
#include <crtdbg.h>
#include <netfw.h>
#include <objbase.h>
#include <oleauto.h>
#include <stdio.h>
#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )
HRESULT WindowsFirewallInitialize(OUT INetFwProfile** fwProfile)
{
HRESULT hr = S_OK;
INetFwMgr* fwMgr = NULL;
INetFwPolicy* fwPolicy = NULL;
_ASSERT(fwProfile != NULL);
*fwProfile = NULL;
do {
// 创建防火墙设置管理器的实例
hr = CoCreateInstance(__uuidof(NetFwMgr), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwMgr), (void**)&fwMgr);
if (FAILED(hr))
{
printf("CoCreateInstance failed: 0x%08lx\n", hr);
break;
}
// 检索本地防火墙策略
hr = fwMgr->get_LocalPolicy(&fwPolicy);
if (FAILED(hr))
{
printf("get_LocalPolicy failed: 0x%08lx\n", hr);
break;
}
// 检索当前有效的防火墙配置文件
hr = fwPolicy->get_CurrentProfile(fwProfile);
if (FAILED(hr))
{
printf("get_CurrentProfile failed: 0x%08lx\n", hr);
break;
}
} while (0);
// 释放本地防火墙策略
if (fwPolicy != NULL)
{
fwPolicy->Release();
}
// 释放防火墙设置管理器
if (fwMgr != NULL)
{
fwMgr->Release();
}
return hr;
}
HRESULT WindowsFirewallIsOn(IN INetFwProfile* fwProfile, OUT BOOL* fwOn)
{
HRESULT hr = S_OK;
VARIANT_BOOL fwEnabled;
_ASSERT(fwProfile != NULL);
_ASSERT(fwOn != NULL);
*fwOn = FALSE;
// 获取防火墙的当前状态
hr = fwProfile->get_FirewallEnabled(&fwEnabled);
if (FAILED(hr))
{
printf("get_FirewallEnabled failed: 0x%08lx\n", hr);
return hr;
}
if (fwEnabled != VARIANT_FALSE)
{
*fwOn = TRUE;
}
return hr;
}
void WindowsFirewallCleanup(IN INetFwProfile* fwProfile)
{
// 释放防火墙配置文件
if (fwProfile != NULL)
{
fwProfile->Release();
}
}
int main()
{
HRESULT hr = S_OK;
INetFwProfile* fwProfile = NULL;
HRESULT comInit = E_FAIL;
// 为当前线程初始化COM库并设置并发模式(这个函数没太理解是干什么用的)
comInit = CoInitializeEx(0, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (comInit != RPC_E_CHANGED_MODE)
{
hr = comInit;
if (FAILED(hr))
{
printf("CoInitializeEx failed: 0x%08lx\n", hr);
return -1;
}
}
//检索当前有效的防火墙配置文件
hr = WindowsFirewallInitialize(&fwProfile);
if (hr != S_OK)
{
printf("WindowsFirewallInitialize failed\n");
return -1;
}
//判断防火墙是否开启
BOOL fwOn;
hr = WindowsFirewallIsOn(fwProfile, &fwOn);
if (hr != S_OK)
{
printf("WindowsFirewallIsOn failed\n");
return -1;
}
if (fwOn)
{
printf("Firewall on\n");
}
else
{
printf("Firewall off\n");
}
WindowsFirewallCleanup(fwProfile);
system("pause");
return 0;
}
我们可以使用cmd命令开启关闭防火墙进行验证
#关闭防火墙
netsh advfirewall set allprofiles state off
#开启防火墙
netsh advfirewall set allprofiles state on
源代码地址:Exercising the Firewall using C++ (Windows) | Microsoft Docs