【小沐学C++】C++ 修改防火墙firewall设置(Windows)

防火墙开发篇系列:
1 C++ 修改防火墙firewall设置(Linux、Ubuntu、CentOS)
2 C++ 修改防火墙firewall设置(Windows)

文章目录

  • 1、简介
    • 1.1 防火墙概述
    • 1.2 入站,还是出站?
    • 1.3 防火墙规则优先级
  • 2、系统界面方式
  • 3、命令行方式
    • 3.1 防火墙基本状态设置
    • 3.2 入站出站规则设置
    • 3.3 其他设置
    • 3.4 telnet检测端口
  • 4、C++方式
    • 4.1 注册表
    • 4.2 COM(Windows XP)
    • 4.3 COM(Windows Vista and later)
  • 5、VB方式
  • 结语

1、简介

防火墙(英语:Firewall)技术是通过有机结合各类用于安全管理与筛选的软件和硬件设备,帮助计算机网络于其内、外网之间构建一道相对隔绝的保护屏障,以保护用户资料与信息安全性的一种技术。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第1张图片

1.1 防火墙概述

所谓“防火墙”是指一种将内部网和公众访问网(如Internet)分开的方法,它实际上是一种建立在现代通信网络技术和信息安全技术基础上的应用性安全技术,隔离技术。越来越多地应用于专用网络与公用网络的互联环境之中,尤其以接入Internet网络为最甚。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第2张图片

1.2 入站,还是出站?

入站是外网的人访问我;出站是我访问外网。
入站开了本机的443端口,意味着外网的人可以通过443端口访问你的HTTPS服务;出站设置一般是允许访问外网IP的443端口。

入站端口:就是别人来访问我的某个端口。比如我设置阻止连接所有站点的入站端口8080,就是所有其他主机不能访问我这台服务器的8080端口。
出站端口:就是我去访问别人的某个端口。比如我设置阻止连接所有站点的出站端口3306,就是我不能访问所有其他网址的3306端口
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第3张图片

1.3 防火墙规则优先级

Windows防火墙的规则扫描有它自己特定的顺序,其优先级为:
1、只允许安全连接
2、阻止连接
3、允许连接
4. 默认规则(如果没有设置,那就是默认阻止)

As soon as a network packet matches a rule, that rule is applied, and processing stops. For example, an arriving network packet is first compared to the authenticated bypass rules. If it matches one, that rule is applied and processing stops. The packet is not compared to the block, allow, or default profile rules. If the packet does not match an authenticated bypass rule, then it is compared to the block rules. If it matches one, the packet is blocked, and processing stops, and so on.

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第4张图片

2、系统界面方式

打开控制面板,点击系统和安全。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第5张图片
点击Windows Defender防火墙。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第6张图片
点击右侧的高级设置。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第7张图片
点击入站规则,然后点击右侧的新建规则。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第8张图片
然后勾选端口,点击下一步。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第9张图片
接着填写开放的端口号(如5000)。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第10张图片
接着如果是允许连接的话,直接点击下一步。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第11张图片
接着直接点击下一步。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第12张图片
接着填写名字和描述,点击完成。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第13张图片
在入站规则中出现了刚才添加的规则。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第14张图片

3、命令行方式

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第15张图片

Win10 如何使用cmd命令行配置防火墙:

3.1 防火墙基本状态设置

# 查看当前防火墙状态:
netsh advfirewall show allprofiles
netsh advfirewall show allprofiles state

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第16张图片

# 恢复初始防火墙设置:
netsh advfirewall reset

# 设置默认输入和输出策略:
# 设置为允许
netsh advfirewall set allprofiles firewallpolicy allowinbound,allowoutbound
# 设置为拒绝
netsh advfirewall set allprofiles firewallpolicy blockinbound,blockoutbound
# 显示默认的入站和出站防火墙行为。
netsh advfirewall show allprofiles firewallpolicy

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第17张图片
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第18张图片

# 显示日志记录设置。
netsh advfirewall show allprofiles logging

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第19张图片

# 开启防火墙:
netsh advfirewall set allprofiles state on

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第20张图片

#关闭防火墙:
netsh advfirewall set allprofiles state off

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第21张图片

3.2 入站出站规则设置

  • 添加入站规则
# 允许
netsh advfirewall firewall add rule name=xiaomu1 dir=in action=allow protocol=tcp localport=5000

# 阻止
netsh advfirewall firewall add rule name=xiaomu1 dir=in action=block protocol=tcp localport=5000

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第22张图片

  • 添加出站规则
# 允许
netsh advfirewall firewall add rule name=xiaomu1 dir=out action=allow protocol=tcp localport=5000

# 阻止
netsh advfirewall firewall add rule name=xiaomu1 dir=out action=block protocol=tcp localport=5000

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第23张图片

  • 删除入站出站规则
# 删除入站允许
netsh advfirewall firewall delete rule name=test001 dir=in action=allow protocol=tcp localport=445

# 删除出站允许
netsh advfirewall firewall delete rule name=test001 dir=out action=allow protocol=tcp localport=445
  • bat批处理文件实现添加防火墙出入站规则:
@echo off

rem 以管理员权限执行命令
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
cd /d "%~dp0"

rem 设置指定端口变量和出入站规则名称
set INPUT_RULE_NAME=xiaomu_in
set OUT_RULE_NAME=xiaomu_out
set PORT=27700-27702,3316,5000-5010

rem 创建入站规则
echo Input Rule
netsh advfirewall firewall show rule name=%INPUT_RULE_NAME% >nul
rem 如果已经存在则先删除
if not ERRORLEVEL 1 (
    netsh advfirewall firewall delete rule name=%INPUT_RULE_NAME% >nul
) 
netsh advfirewall firewall add rule name=%INPUT_RULE_NAME% dir=in action=allow protocol=TCP localport=%PORT%
echo %INPUT_RULE_NAME% Create Successed!

rem 创建出站规则
echo Output Rule
netsh advfirewall firewall show rule name=%OUT_RULE_NAME% >nul
rem 如果已经存在则先删除
if not ERRORLEVEL 1 (
   netsh advfirewall firewall delete rule name=%OUT_RULE_NAME% >nul
) 
netsh advfirewall firewall add rule name=%OUT_RULE_NAME% dir=out action=allow protocol=TCP localport=%PORT%
echo %OUT_RULE_NAME% Create Successed!

echo Done!
pause

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第24张图片

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第25张图片
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第26张图片

3.3 其他设置

  • 允许并阻止ping
    您可以使用netsh来控制给定系统如何响应ping请求以及是否响应。以下两个netsh命令显示了如何阻止然后打开Windows防火墙来ping请求:
netsh advfirewall firewall add rule name="All ICMP V4" dir=in action=block protocol=icmpv4
netsh advfirewall firewall add rule name="All ICMP V4" dir=in action=allow protocol=icmpv4
  • 启用程序
    另一个常见任务是为给定程序打开Windows防火墙。以下示例说明了如何添加使Windows Live Messenger通过Windows防火墙工作的规则:
netsh advfirewall firewall add rule name="Allow Messenger" dir=in action=allow program="C:\programfiles\messenger\msnmsgr.exe"
  • 启用远程管理
    另一个常见要求(尤其是在设置新系统时)是启用远程管理,以便Microsoft Management Console等工具可以连接到远程系统。要打开Windows防火墙进行远程管理,可以使用以下命令:
netsh advfirewall firewall set rule group="remote administration" new enable=yes
  • 启用远程桌面连接
    对设置的大多数服务器系统所做的第一件事就是启用远程桌面连接用于轻松的远程系统管理。以下命令显示如何使用netsh打开Windows防火墙进行远程桌面连接:
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes
  • 导出和导入防火墙设置文件
    配置Windows防火墙后,最好导出设置,以便以后可以轻松地重新应用它们或将其导入另一个系统。
netsh advfirewall export "C:\temp\WFconfiguration.wfw"
netsh advfirewall import "C:\temp\WFconfiguration.wfw"
  • 关闭5900端口
netsh advfirewall firewall add rule name= “deny tcp 5900dir=in protocol=tcp localport=5900 action=block
  • 设置Ip禁止
# remoteip 允许的IP,多个IP用逗号分割
netsh advfirewall firewall add rule name="test" dir=in action=allow protocol=TCP localport=3389,135 remoteip=10.10.12.20,192.168.0.20

3.4 telnet检测端口

完成之后,可以用telnet测试端口是否开放。
打开命令行窗口,输入命令:telnet 127.0.0.1 5000,如果出现下图的界面就说明该端口已经开放。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第27张图片
如果telnet没有安装的话,请按照如下步骤操作。
使用win+R键打开运行程序,在输入框里输入:OptionalFeatures,点击确定。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第28张图片
勾选上Telnet客户端并点击确定,就会开始安装telnet客户端。
重新打开一个cmd窗口输入telnet命令,如下所示表明telnet客户端安装成功。
【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第29张图片

4、C++方式

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第30张图片

4.1 注册表

#include 
 
int main(void)
{
    HKEY hkResult;
    TCHAR szValueName[MAX_PATH] = { 0 }, szData[1024] = { 0 };
    DWORD dwValueNameLen = MAX_PATH, dwDataLen = 1024;
    const TCHAR* lpSubKey = TEXT("SYSTEM\\ControlSet001\\Services\\SharedAccess\\Defaults\\FirewallPolicy\\FirewallRules");
    if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_READ, &hkResult))
    {
        for (DWORD i = 0;; i++)
        {
            if (ERROR_NO_MORE_ITEMS == RegEnumValue(hkResult, i, szValueName, &dwValueNameLen, NULL, NULL, (BYTE*)szData, &dwDataLen))
            {
                break;
            }
            dwValueNameLen = MAX_PATH;
            dwDataLen = 1024;
        }
    }
}

4.2 COM(Windows XP)

/*
	Copyright (c) Microsoft Corporation

	SYNOPSIS

		Sample code for the Windows Firewall COM interface.
*/

#include 
#include 
#include 
#include 
#include 
#include 

#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;

	// Create an instance of the firewall settings manager.
	hr = CoCreateInstance(
		__uuidof(NetFwMgr),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(INetFwMgr),
		(void**)&fwMgr
	);
	if (FAILED(hr))
	{
		printf("CoCreateInstance failed: 0x%08lx\n", hr);
		goto error;
	}

	// Retrieve the local firewall policy.
	hr = fwMgr->get_LocalPolicy(&fwPolicy);
	if (FAILED(hr))
	{
		printf("get_LocalPolicy failed: 0x%08lx\n", hr);
		goto error;
	}

	// Retrieve the firewall profile currently in effect.
	hr = fwPolicy->get_CurrentProfile(fwProfile);
	if (FAILED(hr))
	{
		printf("get_CurrentProfile failed: 0x%08lx\n", hr);
		goto error;
	}

error:

	// Release the local firewall policy.
	if (fwPolicy != NULL)
	{
		fwPolicy->Release();
	}

	// Release the firewall settings manager.
	if (fwMgr != NULL)
	{
		fwMgr->Release();
	}

	return hr;
}


void WindowsFirewallCleanup(IN INetFwProfile* fwProfile)
{
	// Release the firewall profile.
	if (fwProfile != NULL)
	{
		fwProfile->Release();
	}
}


HRESULT WindowsFirewallIsOn(IN INetFwProfile* fwProfile, OUT BOOL* fwOn)
{
	HRESULT hr = S_OK;
	VARIANT_BOOL fwEnabled;

	_ASSERT(fwProfile != NULL);
	_ASSERT(fwOn != NULL);

	*fwOn = FALSE;

	// Get the current state of the firewall.
	hr = fwProfile->get_FirewallEnabled(&fwEnabled);
	if (FAILED(hr))
	{
		printf("get_FirewallEnabled failed: 0x%08lx\n", hr);
		goto error;
	}

	// Check to see if the firewall is on.
	if (fwEnabled != VARIANT_FALSE)
	{
		*fwOn = TRUE;
		printf("The firewall is on.\n");
	}
	else
	{
		printf("The firewall is off.\n");
	}

error:

	return hr;
}


HRESULT WindowsFirewallTurnOn(IN INetFwProfile* fwProfile)
{
	HRESULT hr = S_OK;
	BOOL fwOn;

	_ASSERT(fwProfile != NULL);

	// Check to see if the firewall is off.
	hr = WindowsFirewallIsOn(fwProfile, &fwOn);
	if (FAILED(hr))
	{
		printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);
		goto error;
	}

	// If it is, turn it on.
	if (!fwOn)
	{
		// Turn the firewall on.
		hr = fwProfile->put_FirewallEnabled(VARIANT_TRUE);
		if (FAILED(hr))
		{
			printf("put_FirewallEnabled failed: 0x%08lx\n", hr);
			goto error;
		}

		printf("The firewall is now on.\n");
	}

error:

	return hr;
}


HRESULT WindowsFirewallTurnOff(IN INetFwProfile* fwProfile)
{
	HRESULT hr = S_OK;
	BOOL fwOn;

	_ASSERT(fwProfile != NULL);

	// Check to see if the firewall is on.
	hr = WindowsFirewallIsOn(fwProfile, &fwOn);
	if (FAILED(hr))
	{
		printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);
		goto error;
	}

	// If it is, turn it off.
	if (fwOn)
	{
		// Turn the firewall off.
		hr = fwProfile->put_FirewallEnabled(VARIANT_FALSE);
		if (FAILED(hr))
		{
			printf("put_FirewallEnabled failed: 0x%08lx\n", hr);
			goto error;
		}

		printf("The firewall is now off.\n");
	}

error:

	return hr;
}


HRESULT WindowsFirewallAppIsEnabled(
	IN INetFwProfile* fwProfile,
	IN const wchar_t* fwProcessImageFileName,
	OUT BOOL* fwAppEnabled
)
{
	HRESULT hr = S_OK;
	BSTR fwBstrProcessImageFileName = NULL;
	VARIANT_BOOL fwEnabled;
	INetFwAuthorizedApplication* fwApp = NULL;
	INetFwAuthorizedApplications* fwApps = NULL;

	_ASSERT(fwProfile != NULL);
	_ASSERT(fwProcessImageFileName != NULL);
	_ASSERT(fwAppEnabled != NULL);

	*fwAppEnabled = FALSE;

	// Retrieve the authorized application collection.
	hr = fwProfile->get_AuthorizedApplications(&fwApps);
	if (FAILED(hr))
	{
		printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);
		goto error;
	}

	// Allocate a BSTR for the process image file name.
	fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);
	if (fwBstrProcessImageFileName == NULL)
	{
		hr = E_OUTOFMEMORY;
		printf("SysAllocString failed: 0x%08lx\n", hr);
		goto error;
	}

	// Attempt to retrieve the authorized application.
	hr = fwApps->Item(fwBstrProcessImageFileName, &fwApp);
	if (SUCCEEDED(hr))
	{
		// Find out if the authorized application is enabled.
		hr = fwApp->get_Enabled(&fwEnabled);
		if (FAILED(hr))
		{
			printf("get_Enabled failed: 0x%08lx\n", hr);
			goto error;
		}

		if (fwEnabled != VARIANT_FALSE)
		{
			// The authorized application is enabled.
			*fwAppEnabled = TRUE;

			printf(
				"Authorized application %lS is enabled in the firewall.\n",
				fwProcessImageFileName
			);
		}
		else
		{
			printf(
				"Authorized application %lS is disabled in the firewall.\n",
				fwProcessImageFileName
			);
		}
	}
	else
	{
		// The authorized application was not in the collection.
		hr = S_OK;

		printf(
			"Authorized application %lS is disabled in the firewall.\n",
			fwProcessImageFileName
		);
	}

error:

	// Free the BSTR.
	SysFreeString(fwBstrProcessImageFileName);

	// Release the authorized application instance.
	if (fwApp != NULL)
	{
		fwApp->Release();
	}

	// Release the authorized application collection.
	if (fwApps != NULL)
	{
		fwApps->Release();
	}

	return hr;
}


HRESULT WindowsFirewallAddApp(
	IN INetFwProfile* fwProfile,
	IN const wchar_t* fwProcessImageFileName,
	IN const wchar_t* fwName
)
{
	HRESULT hr = S_OK;
	BOOL fwAppEnabled;
	BSTR fwBstrName = NULL;
	BSTR fwBstrProcessImageFileName = NULL;
	INetFwAuthorizedApplication* fwApp = NULL;
	INetFwAuthorizedApplications* fwApps = NULL;

	_ASSERT(fwProfile != NULL);
	_ASSERT(fwProcessImageFileName != NULL);
	_ASSERT(fwName != NULL);

	// First check to see if the application is already authorized.
	hr = WindowsFirewallAppIsEnabled(
		fwProfile,
		fwProcessImageFileName,
		&fwAppEnabled
	);
	if (FAILED(hr))
	{
		printf("WindowsFirewallAppIsEnabled failed: 0x%08lx\n", hr);
		goto error;
	}

	// Only add the application if it isn't already authorized.
	if (!fwAppEnabled)
	{
		// Retrieve the authorized application collection.
		hr = fwProfile->get_AuthorizedApplications(&fwApps);
		if (FAILED(hr))
		{
			printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);
			goto error;
		}

		// Create an instance of an authorized application.
		hr = CoCreateInstance(
			__uuidof(NetFwAuthorizedApplication),
			NULL,
			CLSCTX_INPROC_SERVER,
			__uuidof(INetFwAuthorizedApplication),
			(void**)&fwApp
		);
		if (FAILED(hr))
		{
			printf("CoCreateInstance failed: 0x%08lx\n", hr);
			goto error;
		}

		// Allocate a BSTR for the process image file name.
		fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);
		if (fwBstrProcessImageFileName == NULL)
		{
			hr = E_OUTOFMEMORY;
			printf("SysAllocString failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the process image file name.
		hr = fwApp->put_ProcessImageFileName(fwBstrProcessImageFileName);
		if (FAILED(hr))
		{
			printf("put_ProcessImageFileName failed: 0x%08lx\n", hr);
			goto error;
		}

		// Allocate a BSTR for the application friendly name.
		fwBstrName = SysAllocString(fwName);
		if (SysStringLen(fwBstrName) == 0)
		{
			hr = E_OUTOFMEMORY;
			printf("SysAllocString failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the application friendly name.
		hr = fwApp->put_Name(fwBstrName);
		if (FAILED(hr))
		{
			printf("put_Name failed: 0x%08lx\n", hr);
			goto error;
		}

		// Add the application to the collection.
		hr = fwApps->Add(fwApp);
		if (FAILED(hr))
		{
			printf("Add failed: 0x%08lx\n", hr);
			goto error;
		}

		printf(
			"Authorized application %lS is now enabled in the firewall.\n",
			fwProcessImageFileName
		);
	}

error:

	// Free the BSTRs.
	SysFreeString(fwBstrName);
	SysFreeString(fwBstrProcessImageFileName);

	// Release the authorized application instance.
	if (fwApp != NULL)
	{
		fwApp->Release();
	}

	// Release the authorized application collection.
	if (fwApps != NULL)
	{
		fwApps->Release();
	}

	return hr;
}


HRESULT WindowsFirewallPortIsEnabled(
	IN INetFwProfile* fwProfile,
	IN LONG portNumber,
	IN NET_FW_IP_PROTOCOL ipProtocol,
	OUT BOOL* fwPortEnabled
)
{
	HRESULT hr = S_OK;
	VARIANT_BOOL fwEnabled;
	INetFwOpenPort* fwOpenPort = NULL;
	INetFwOpenPorts* fwOpenPorts = NULL;

	_ASSERT(fwProfile != NULL);
	_ASSERT(fwPortEnabled != NULL);

	*fwPortEnabled = FALSE;

	// Retrieve the globally open ports collection.
	hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts);
	if (FAILED(hr))
	{
		printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);
		goto error;
	}

	// Attempt to retrieve the globally open port.
	hr = fwOpenPorts->Item(portNumber, ipProtocol, &fwOpenPort);
	if (SUCCEEDED(hr))
	{
		// Find out if the globally open port is enabled.
		hr = fwOpenPort->get_Enabled(&fwEnabled);
		if (FAILED(hr))
		{
			printf("get_Enabled failed: 0x%08lx\n", hr);
			goto error;
		}

		if (fwEnabled != VARIANT_FALSE)
		{
			// The globally open port is enabled.
			*fwPortEnabled = TRUE;

			printf("Port %ld is open in the firewall.\n", portNumber);
		}
		else
		{
			printf("Port %ld is not open in the firewall.\n", portNumber);
		}
	}
	else
	{
		// The globally open port was not in the collection.
		hr = S_OK;

		printf("Port %ld is not open in the firewall.\n", portNumber);
	}

error:

	// Release the globally open port.
	if (fwOpenPort != NULL)
	{
		fwOpenPort->Release();
	}

	// Release the globally open ports collection.
	if (fwOpenPorts != NULL)
	{
		fwOpenPorts->Release();
	}

	return hr;
}


HRESULT WindowsFirewallPortAdd(
	IN INetFwProfile* fwProfile,
	IN LONG portNumber,
	IN NET_FW_IP_PROTOCOL ipProtocol,
	IN const wchar_t* name
)
{
	HRESULT hr = S_OK;
	BOOL fwPortEnabled;
	BSTR fwBstrName = NULL;
	INetFwOpenPort* fwOpenPort = NULL;
	INetFwOpenPorts* fwOpenPorts = NULL;

	_ASSERT(fwProfile != NULL);
	_ASSERT(name != NULL);

	// First check to see if the port is already added.
	hr = WindowsFirewallPortIsEnabled(
		fwProfile,
		portNumber,
		ipProtocol,
		&fwPortEnabled
	);
	if (FAILED(hr))
	{
		printf("WindowsFirewallPortIsEnabled failed: 0x%08lx\n", hr);
		goto error;
	}

	// Only add the port if it isn't already added.
	if (!fwPortEnabled)
	{
		// Retrieve the collection of globally open ports.
		hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts);
		if (FAILED(hr))
		{
			printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);
			goto error;
		}

		// Create an instance of an open port.
		hr = CoCreateInstance(
			__uuidof(NetFwOpenPort),
			NULL,
			CLSCTX_INPROC_SERVER,
			__uuidof(INetFwOpenPort),
			(void**)&fwOpenPort
		);
		if (FAILED(hr))
		{
			printf("CoCreateInstance failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the port number.
		hr = fwOpenPort->put_Port(portNumber);
		if (FAILED(hr))
		{
			printf("put_Port failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the IP protocol.
		hr = fwOpenPort->put_Protocol(ipProtocol);
		if (FAILED(hr))
		{
			printf("put_Protocol failed: 0x%08lx\n", hr);
			goto error;
		}

		// Allocate a BSTR for the friendly name of the port.
		fwBstrName = SysAllocString(name);
		if (SysStringLen(fwBstrName) == 0)
		{
			hr = E_OUTOFMEMORY;
			printf("SysAllocString failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the friendly name of the port.
		hr = fwOpenPort->put_Name(fwBstrName);
		if (FAILED(hr))
		{
			printf("put_Name failed: 0x%08lx\n", hr);
			goto error;
		}

		// Opens the port and adds it to the collection.
		hr = fwOpenPorts->Add(fwOpenPort);
		if (FAILED(hr))
		{
			printf("Add failed: 0x%08lx\n", hr);
			goto error;
		}

		printf("Port %ld is now open in the firewall.\n", portNumber);
	}

error:

	// Free the BSTR.
	SysFreeString(fwBstrName);

	// Release the open port instance.
	if (fwOpenPort != NULL)
	{
		fwOpenPort->Release();
	}

	// Release the globally open ports collection.
	if (fwOpenPorts != NULL)
	{
		fwOpenPorts->Release();
	}

	return hr;
}


int __cdecl wmain(int argc, wchar_t* argv[])
{
	HRESULT hr = S_OK;
	HRESULT comInit = E_FAIL;
	INetFwProfile* fwProfile = NULL;

	// Initialize COM.
	comInit = CoInitializeEx(
		0,
		COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE
	);

	// Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
	// initialized with a different mode. Since we don't care what the mode is,
	// we'll just use the existing mode.
	if (comInit != RPC_E_CHANGED_MODE)
	{
		hr = comInit;
		if (FAILED(hr))
		{
			printf("CoInitializeEx failed: 0x%08lx\n", hr);
			goto error;
		}
	}

	// Retrieve the firewall profile currently in effect.
	hr = WindowsFirewallInitialize(&fwProfile);
	if (FAILED(hr))
	{
		printf("WindowsFirewallInitialize failed: 0x%08lx\n", hr);
		goto error;
	}

	// Turn off the firewall.
	/*hr = WindowsFirewallTurnOff(fwProfile);
	if (FAILED(hr))
	{
		printf("WindowsFirewallTurnOff failed: 0x%08lx\n", hr);
		goto error;
	}*/

	// Turn on the firewall.
	hr = WindowsFirewallTurnOn(fwProfile);
	if (FAILED(hr))
	{
		printf("WindowsFirewallTurnOn failed: 0x%08lx\n", hr);
		goto error;
	}

	// Add Windows Messenger to the authorized application collection.
	hr = WindowsFirewallAddApp(
		fwProfile,
		//L"%ProgramFiles%\\Messenger\\msmsgs.exe",
		L"C:\\program files\\google\\chrome\\application\\chrome.exe",
		L"XiaoMu_add_exe"
	);
	if (FAILED(hr))
	{
		printf("WindowsFirewallAddApp failed: 0x%08lx\n", hr);
		goto error;
	}

	// Add TCP::80 to list of globally open ports.
	hr = WindowsFirewallPortAdd(fwProfile, 12345, NET_FW_IP_PROTOCOL_TCP, L"XiaoMu_add_tcp");
	if (FAILED(hr))
	{
		printf("WindowsFirewallPortAdd failed: 0x%08lx\n", hr);
		goto error;
	}

error:

	// Release the firewall profile.
	WindowsFirewallCleanup(fwProfile);

	// Uninitialize COM.
	if (SUCCEEDED(comInit))
	{
		CoUninitialize();
	}

	return 0;
}

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第31张图片

4.3 COM(Windows Vista and later)

高级安全 Windows 防火墙和此处记录的相关防火墙技术使开发人员能够共享 Internet 连接、使用防火墙保护连接并提供网络地址转换 (NAT)。

微软已经发布了几个版本的防火墙产品,每个版本都建立在以前的技术之上。当前版本“高级安全 Windows 防火墙”允许创建极其具体的防火墙规则。

  • 具体技术如下(此处从最新到最旧列出):

    • 高级安全 Windows 防火墙是最新版本。它最初与Windows Vista一起发布。
    • Windows Firewall 最初是作为 Windows XP Service Pack 2 (SP2) 的一个组件发布的。
    • IPv6 Internet Connection Firewall 作为 Windows XP 高级网络包的组件发布。它在后续版本的 Windows 中不可用。
    • Internet 连接共享和 Internet 连接防火墙最初是在 Windows XP 中发布的,在 Windows Vista 中受支持。它可能在后续版本的 Windows 中被更改或不可用。
  • 添加防火墙规则
    This C++ file includes sample code that adds a LAN rule to the
    currently active profiles using the Microsoft Windows Firewall
    APIs.

#include 
#include 
#include 

#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )


// Forward declarations
HRESULT     WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2);


// Instantiate INetFwPolicy2
HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2)
{
	HRESULT hr = S_OK;

	hr = CoCreateInstance(
		__uuidof(NetFwPolicy2),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(INetFwPolicy2),
		(void**)ppNetFwPolicy2);

	if (FAILED(hr))
	{
		printf("CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

Cleanup:
	return hr;
}

int main(int argc, TCHAR* argv[])
{
	HRESULT hrComInit = S_OK;
	HRESULT hr = S_OK;

	INetFwPolicy2 *pNetFwPolicy2 = NULL;
	INetFwRules *pFwRules = NULL;
	INetFwRule *pFwRule = NULL;

	long CurrentProfilesBitMask = 0;

	BSTR bstrRuleName = SysAllocString(L"XiaoMu_0129");
	BSTR bstrRuleDescription = SysAllocString(L"Allow incoming network traffic over port 2400 coming from LAN interface type");
	BSTR bstrRuleGroup = SysAllocString(L"Sample Rule Group");
	BSTR bstrRuleLPorts = SysAllocString(L"2400-2450");
	BSTR bstrRuleInterfaceType = SysAllocString(L"LAN");

	// Initialize COM.
	hrComInit = CoInitializeEx(
		0,
		COINIT_APARTMENTTHREADED
	);

	// Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
	// initialized with a different mode. Since we don't care what the mode is,
	// we'll just use the existing mode.
	if (hrComInit != RPC_E_CHANGED_MODE)
	{
		if (FAILED(hrComInit))
		{
			printf("CoInitializeEx failed: 0x%08lx\n", hrComInit);
			goto Cleanup;
		}
	}

	// Retrieve INetFwPolicy2
	hr = WFCOMInitialize(&pNetFwPolicy2);
	if (FAILED(hr))
	{
		goto Cleanup;
	}

	// Retrieve INetFwRules
	hr = pNetFwPolicy2->get_Rules(&pFwRules);
	if (FAILED(hr))
	{
		printf("get_Rules failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

	// Retrieve Current Profiles bitmask
	hr = pNetFwPolicy2->get_CurrentProfileTypes(&CurrentProfilesBitMask);
	if (FAILED(hr))
	{
		printf("get_CurrentProfileTypes failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

	// When possible we avoid adding firewall rules to the Public profile.
	// If Public is currently active and it is not the only active profile, we remove it from the bitmask
	if ((CurrentProfilesBitMask & NET_FW_PROFILE2_PUBLIC) &&
		(CurrentProfilesBitMask != NET_FW_PROFILE2_PUBLIC))
	{
		CurrentProfilesBitMask ^= NET_FW_PROFILE2_PUBLIC;
	}

	// Create a new Firewall Rule object.
	hr = CoCreateInstance(
		__uuidof(NetFwRule),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(INetFwRule),
		(void**)&pFwRule);
	if (FAILED(hr))
	{
		printf("CoCreateInstance for Firewall Rule failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

	// Populate the Firewall Rule object
	pFwRule->put_Name(bstrRuleName);
	pFwRule->put_Description(bstrRuleDescription);
	pFwRule->put_Protocol(NET_FW_IP_PROTOCOL_TCP);
	pFwRule->put_LocalPorts(bstrRuleLPorts);
	pFwRule->put_Grouping(bstrRuleGroup);
	pFwRule->put_InterfaceTypes(bstrRuleInterfaceType);
	pFwRule->put_Profiles(CurrentProfilesBitMask);
	pFwRule->put_Action(NET_FW_ACTION_ALLOW);
	pFwRule->put_Enabled(VARIANT_TRUE);

	// Add the Firewall Rule
	hr = pFwRules->Add(pFwRule);
	if (FAILED(hr))
	{
		printf("Firewall Rule Add failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

Cleanup:

	// Free BSTR's
	SysFreeString(bstrRuleName);
	SysFreeString(bstrRuleDescription);
	SysFreeString(bstrRuleGroup);
	SysFreeString(bstrRuleLPorts);
	SysFreeString(bstrRuleInterfaceType);

	// Release the INetFwRule object
	if (pFwRule != NULL)
	{
		pFwRule->Release();
	}

	// Release the INetFwRules object
	if (pFwRules != NULL)
	{
		pFwRules->Release();
	}

	// Release the INetFwPolicy2 object
	if (pNetFwPolicy2 != NULL)
	{
		pNetFwPolicy2->Release();
	}

	// Uninitialize COM.
	if (SUCCEEDED(hrComInit))
	{
		CoUninitialize();
	}

	printf("OK.\n");
	getchar();
	return 0;

}

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第32张图片

  • 遍历所有的防火墙规则
/********************************************************************++
Copyright (C) Microsoft. All Rights Reserved.

Abstract:
    This C++ file includes sample code for enumerating Windows Firewall
    rules using the Microsoft Windows Firewall APIs.

********************************************************************/

#include 
#include 
#include 
#include 
#include 

#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )

#define NET_FW_IP_PROTOCOL_TCP_NAME L"TCP"
#define NET_FW_IP_PROTOCOL_UDP_NAME L"UDP"

#define NET_FW_RULE_DIR_IN_NAME L"In"
#define NET_FW_RULE_DIR_OUT_NAME L"Out"

#define NET_FW_RULE_ACTION_BLOCK_NAME L"Block"
#define NET_FW_RULE_ACTION_ALLOW_NAME L"Allow"

#define NET_FW_RULE_ENABLE_IN_NAME L"TRUE"
#define NET_FW_RULE_DISABLE_IN_NAME L"FALSE"


// Forward declarations
void        DumpFWRulesInCollection(INetFwRule* FwRule);
HRESULT     WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2);


int __cdecl main()
{
    HRESULT hrComInit = S_OK;
    HRESULT hr = S_OK;

    ULONG cFetched = 0; 
    CComVariant var;

    IUnknown *pEnumerator;
    IEnumVARIANT* pVariant = NULL;

    INetFwPolicy2 *pNetFwPolicy2 = NULL;
    INetFwRules *pFwRules = NULL;
    INetFwRule *pFwRule = NULL;

    long fwRuleCount;

    // Initialize COM.
    hrComInit = CoInitializeEx(
                    0,
                    COINIT_APARTMENTTHREADED
                    );

    // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
    // initialized with a different mode. Since we don't care what the mode is,
    // we'll just use the existing mode.
    if (hrComInit != RPC_E_CHANGED_MODE)
    {
        if (FAILED(hrComInit))
        {
            wprintf(L"CoInitializeEx failed: 0x%08lx\n", hrComInit);
            goto Cleanup;
        }
    }

    // Retrieve INetFwPolicy2
    hr = WFCOMInitialize(&pNetFwPolicy2);
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // Retrieve INetFwRules
    hr = pNetFwPolicy2->get_Rules(&pFwRules);
    if (FAILED(hr))
    {
        wprintf(L"get_Rules failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Obtain the number of Firewall rules
    hr = pFwRules->get_Count(&fwRuleCount);
    if (FAILED(hr))
    {
        wprintf(L"get_Count failed: 0x%08lx\n", hr);
        goto Cleanup;
    }
    
    wprintf(L"The number of rules in the Windows Firewall are %d\n", fwRuleCount);

    // Iterate through all of the rules in pFwRules
    pFwRules->get__NewEnum(&pEnumerator);

    if(pEnumerator)
    {
        hr = pEnumerator->QueryInterface(__uuidof(IEnumVARIANT), (void **) &pVariant);
    }

    while(SUCCEEDED(hr) && hr != S_FALSE)
    {
        var.Clear();
        hr = pVariant->Next(1, &var, &cFetched);

        if (S_FALSE != hr)
        {
            if (SUCCEEDED(hr))
            {
                hr = var.ChangeType(VT_DISPATCH);
            }
            if (SUCCEEDED(hr))
            {
                hr = (V_DISPATCH(&amp;var))->QueryInterface(__uuidof(INetFwRule), reinterpret_cast<void**>(&amp;pFwRule));
            }

            if (SUCCEEDED(hr))
            {
                // Output the properties of this rule
                DumpFWRulesInCollection(pFwRule);
            }
        }
    }
 
Cleanup:

    // Release pFwRule
    if (pFwRule != NULL)
    {
        pFwRule->Release();
    }

    // Release INetFwPolicy2
    if (pNetFwPolicy2 != NULL)
    {
        pNetFwPolicy2->Release();
    }

    // Uninitialize COM.
    if (SUCCEEDED(hrComInit))
    {
        CoUninitialize();
    }
   
    return 0;
}


// Output properties of a Firewall rule 
void DumpFWRulesInCollection(INetFwRule* FwRule)
{
    variant_t InterfaceArray;
    variant_t InterfaceString;  

    VARIANT_BOOL bEnabled;
    BSTR bstrVal;

    long lVal = 0;
    long lProfileBitmask = 0;

    NET_FW_RULE_DIRECTION fwDirection;
    NET_FW_ACTION fwAction;

    struct ProfileMapElement 
    {
        NET_FW_PROFILE_TYPE2 Id;
        LPCWSTR Name;
    };

    ProfileMapElement ProfileMap[3];
    ProfileMap[0].Id = NET_FW_PROFILE2_DOMAIN;
    ProfileMap[0].Name = L"Domain";
    ProfileMap[1].Id = NET_FW_PROFILE2_PRIVATE;
    ProfileMap[1].Name = L"Private";
    ProfileMap[2].Id = NET_FW_PROFILE2_PUBLIC;
    ProfileMap[2].Name = L"Public";

    wprintf(L"---------------------------------------------\n");

    if (SUCCEEDED(FwRule->get_Name(&amp;bstrVal)))
    {
        wprintf(L"Name:             %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Description(&amp;bstrVal)))
    {
        wprintf(L"Description:      %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_ApplicationName(&amp;bstrVal)))
    {
        wprintf(L"Application Name: %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_ServiceName(&amp;bstrVal)))
    {
        wprintf(L"Service Name:     %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Protocol(&amp;lVal)))
    {
        switch(lVal)
        {
            case NET_FW_IP_PROTOCOL_TCP: 

                wprintf(L"IP Protocol:      %s\n", NET_FW_IP_PROTOCOL_TCP_NAME);
                break;

            case NET_FW_IP_PROTOCOL_UDP: 

                wprintf(L"IP Protocol:      %s\n", NET_FW_IP_PROTOCOL_UDP_NAME);
                break;

            default:

                break;
        }

        if(lVal != NET_FW_IP_VERSION_V4 &amp;&amp; lVal != NET_FW_IP_VERSION_V6)
        {
            if (SUCCEEDED(FwRule->get_LocalPorts(&amp;bstrVal)))
            {
                wprintf(L"Local Ports:      %s\n", bstrVal);
            }

            if (SUCCEEDED(FwRule->get_RemotePorts(&amp;bstrVal)))
            {
                wprintf(L"Remote Ports:      %s\n", bstrVal);
            }
        }
        else
        {
            if (SUCCEEDED(FwRule->get_IcmpTypesAndCodes(&amp;bstrVal)))
            {
                wprintf(L"ICMP TypeCode:      %s\n", bstrVal);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_LocalAddresses(&amp;bstrVal)))
    {
        wprintf(L"LocalAddresses:   %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_RemoteAddresses(&amp;bstrVal)))
    {
        wprintf(L"RemoteAddresses:  %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Profiles(&amp;lProfileBitmask)))
    {
        // The returned bitmask can have more than 1 bit set if multiple profiles 
        //   are active or current at the same time

        for (int i=0; i<3; i++)
        {
            if ( lProfileBitmask & ProfileMap[i].Id  )
            {
                wprintf(L"Profile:  %s\n", ProfileMap[i].Name);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_Direction(&amp;fwDirection)))
    {
        switch(fwDirection)
        {
            case NET_FW_RULE_DIR_IN:

                wprintf(L"Direction:        %s\n", NET_FW_RULE_DIR_IN_NAME);
                break;

            case NET_FW_RULE_DIR_OUT:

                wprintf(L"Direction:        %s\n", NET_FW_RULE_DIR_OUT_NAME);
                break;

            default:

                break;
        }
    }

    if (SUCCEEDED(FwRule->get_Action(&amp;fwAction)))
    {
        switch(fwAction)
        {
            case NET_FW_ACTION_BLOCK:

                wprintf(L"Action:           %s\n", NET_FW_RULE_ACTION_BLOCK_NAME);
                break;

            case NET_FW_ACTION_ALLOW:

                wprintf(L"Action:           %s\n", NET_FW_RULE_ACTION_ALLOW_NAME);
                break;

            default:

                break;
        }
    }

    if (SUCCEEDED(FwRule->get_Interfaces(&amp;InterfaceArray)))
    {
        if(InterfaceArray.vt != VT_EMPTY)
        {
            SAFEARRAY    *pSa = NULL;

            pSa = InterfaceArray.parray;

            for(long index= pSa->rgsabound->lLbound; index < (long)pSa->rgsabound->cElements; index++)
            {
                SafeArrayGetElement(pSa, &amp;index, &amp;InterfaceString);
                wprintf(L"Interfaces:       %s\n", (BSTR)InterfaceString.bstrVal);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_InterfaceTypes(&amp;bstrVal)))
    {
        wprintf(L"Interface Types:  %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Enabled(&amp;bEnabled)))
    {
        if (bEnabled)
        {
            wprintf(L"Enabled:          %s\n", NET_FW_RULE_ENABLE_IN_NAME);
        }
        else
        {
            wprintf(L"Enabled:          %s\n", NET_FW_RULE_DISABLE_IN_NAME);
        }
    }

    if (SUCCEEDED(FwRule->get_Grouping(&amp;bstrVal)))
    {
        wprintf(L"Grouping:         %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_EdgeTraversal(&amp;bEnabled)))
    {
        if (bEnabled)
        {
            wprintf(L"Edge Traversal:   %s\n", NET_FW_RULE_ENABLE_IN_NAME);
        }
        else
        {
            wprintf(L"Edge Traversal:   %s\n", NET_FW_RULE_DISABLE_IN_NAME);
        }
    }
}


// Instantiate INetFwPolicy2
HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2)
{
    HRESULT hr = S_OK;

    hr = CoCreateInstance(
        __uuidof(NetFwPolicy2), 
        NULL, 
        CLSCTX_INPROC_SERVER, 
        __uuidof(INetFwPolicy2), 
        (void**)ppNetFwPolicy2);

    if (FAILED(hr))
    {
        wprintf(L"CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr);
        goto Cleanup;        
    }

Cleanup:
    return hr;
}

5、VB方式

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第33张图片

'  This VBScript file includes sample code that enumerates
'  Windows Firewall rules using the Microsoft Windows Firewall APIs.


Option Explicit

Dim CurrentProfiles
Dim InterfaceArray
Dim LowerBound
Dim UpperBound
Dim iterate
Dim rule

' Profile Type
Const NET_FW_PROFILE2_DOMAIN = 1
Const NET_FW_PROFILE2_PRIVATE = 2
Const NET_FW_PROFILE2_PUBLIC = 4

' Protocol
Const NET_FW_IP_PROTOCOL_TCP = 6
Const NET_FW_IP_PROTOCOL_UDP = 17
Const NET_FW_IP_PROTOCOL_ICMPv4 = 1
Const NET_FW_IP_PROTOCOL_ICMPv6 = 58

' Direction
Const NET_FW_RULE_DIR_IN = 1
Const NET_FW_RULE_DIR_OUT = 2

' Action
Const NET_FW_ACTION_BLOCK = 0
Const NET_FW_ACTION_ALLOW = 1


' Create the FwPolicy2 object.
Dim fwPolicy2
Set fwPolicy2 = CreateObject("HNetCfg.FwPolicy2")

CurrentProfiles = fwPolicy2.CurrentProfileTypes

'// The returned 'CurrentProfiles' bitmask can have more than 1 bit set if multiple profiles 
'//   are active or current at the same time

if ( CurrentProfiles AND NET_FW_PROFILE2_DOMAIN ) then
   WScript.Echo("Domain Firewall Profile is active")
end if

if ( CurrentProfiles AND NET_FW_PROFILE2_PRIVATE ) then
   WScript.Echo("Private Firewall Profile is active")
end if

if ( CurrentProfiles AND NET_FW_PROFILE2_PUBLIC ) then
   WScript.Echo("Public Firewall Profile is active")
end if

' Get the Rules object
Dim RulesObject
Set RulesObject = fwPolicy2.Rules

' Print all the rules in currently active firewall profiles.
WScript.Echo("Rules:")

For Each rule In Rulesobject
    if rule.Profiles And CurrentProfiles then
        WScript.Echo("  Rule Name:          " & rule.Name)
        WScript.Echo("   ----------------------------------------------")
        WScript.Echo("  Description:        " & rule.Description)
        WScript.Echo("  Application Name:   " & rule.ApplicationName)
        WScript.Echo("  Service Name:       " & rule.ServiceName)
        Select Case rule.Protocol
            Case NET_FW_IP_PROTOCOL_TCP    WScript.Echo("  IP Protocol:        TCP.")
            Case NET_FW_IP_PROTOCOL_UDP    WScript.Echo("  IP Protocol:        UDP.")
            Case NET_FW_IP_PROTOCOL_ICMPv4 WScript.Echo("  IP Protocol:        UDP.")
            Case NET_FW_IP_PROTOCOL_ICMPv6 WScript.Echo("  IP Protocol:        UDP.")
            Case Else                      WScript.Echo("  IP Protocol:        " & rule.Protocol)
        End Select
        if rule.Protocol = NET_FW_IP_PROTOCOL_TCP or rule.Protocol = NET_FW_IP_PROTOCOL_UDP then
            WScript.Echo("  Local Ports:        " & rule.LocalPorts)
            WScript.Echo("  Remote Ports:       " & rule.RemotePorts)
            WScript.Echo("  LocalAddresses:     " & rule.LocalAddresses)
            WScript.Echo("  RemoteAddresses:    " & rule.RemoteAddresses)
        end if
        if rule.Protocol = NET_FW_IP_PROTOCOL_ICMPv4 or rule.Protocol = NET_FW_IP_PROTOCOL_ICMPv6 then
            WScript.Echo("  ICMP Type and Code:    " & rule.IcmpTypesAndCodes)
        end if
        Select Case rule.Direction
            Case NET_FW_RULE_DIR_IN  WScript.Echo("  Direction:          In")
            Case NET_FW_RULE_DIR_OUT WScript.Echo("  Direction:          Out")
        End Select
        WScript.Echo("  Enabled:            " & rule.Enabled)
        WScript.Echo("  Edge:               " & rule.EdgeTraversal)
        Select Case rule.Action
            Case NET_FW_ACTION_ALLOW  WScript.Echo("  Action:             Allow")
            Case NET_FW_ACTION_BLOCk  WScript.Echo("  Action:             Block")
        End Select
        WScript.Echo("  Grouping:           " & rule.Grouping)
        WScript.Echo("  Edge:               " & rule.EdgeTraversal)
        WScript.Echo("  Interface Types:    " & rule.InterfaceTypes)
        InterfaceArray = rule.Interfaces
        if IsEmpty(InterfaceArray) then
            WScript.Echo("  Interfaces:         All")
        else
            LowerBound = LBound(InterfaceArray)
            UpperBound = UBound(InterfaceArray)
            WScript.Echo("  Interfaces:     ")
            for iterate = LowerBound To UpperBound
                WScript.Echo("       " & InterfaceArray(iterate))
            Next
        end if

        WScript.Echo("")
    end if
Next

【小沐学C++】C++ 修改防火墙firewall设置(Windows)_第34张图片

flask默认开启的网站是本地的127.0.0.1:5000
现在把已经有的本机访问改成局域网访问:app.run(host=’0.0.0.0’,port=8080)

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

你可能感兴趣的:(C/C++,windows,c++,网络,防火墙,flask)