Windows 防火墙控制

通常,我们在初次执行某些网络应用程序的时候,Windows防火墙会提示我们是否阻止该程序的网络连接,如下图:
本文主要介绍如何使用COM接口编程来操作Windows防火墙,使程序自动的解除阻止(即将本程序添加到防火墙的例外列表中),打开防火墙,关闭防火墙等。
 
1. 获得防火墙接口 INetFwProfile
INetFwProfile * m_pIFirewall = NULL ;    

INetFwMgr * pIFirewallMgr = NULL;    
INetFwPolicy * pIFirewallPolicy = NULL;    

CoCreateInstance(__uuidof(NetFwMgr),NULL,CLSCTX_INPROC_SERVER,    
                                                __uuidof(INetFwMgr),(void**)&pIFirewallMgr);    

pIFirewallMgr->get_LocalPolicy(&pIFirewallPolicy);    

pIFirewallPolicy->get_CurrentProfile(&m_pIFirewall);
2. 判断是否已经打开防火墙
VARIANT_BOOL varbOpen = VARIANT_FALSE ;    
m_pIFirewall->get_FirewallEnabled(&varbOpen)
3. 打开防火墙
 
m_pIFirewall->put_FirewallEnabled(VARIANT_TRUE);
 
4. 关闭防火墙
 
m_pIFirewall->put_FirewallEnabled(VARIANT_FALSE);
 
5. 判断一个应用程序是否解除阻止
INetFwAuthorizedApplications* pIFirewallApps = NULL;    
INetFwAuthorizedApplication * pIFirewallApp        = NULL;    

m_pIFirewall->get_AuthorizedApplications(&pIFirewallApps);    

pIFirewallApps->Item(bstrAppPath,&pIFirewallApp);    

VARIANT_BOOL varbEnabled ;    
pIFirewallApp->get_Enabled(&varbEnabled);
 
6. 解除一个应用程序的阻止
INetFwAuthorizedApplications* pIFirewallApps = NULL;    
INetFwAuthorizedApplication * pIFirewallApp        = NULL;    

m_pIFirewall->get_AuthorizedApplications(&pIFirewallApps);    

CoCreateInstance(__uuidof(NetFwAuthorizedApplication),NULL,CLSCTX_INPROC_SERVER,    
                        __uuidof(INetFwAuthorizedApplication),(void**)&pIFirewallApp);    

pIFirewallApp->put_ProcessImageFileName(bstrAppPath);    

pIFirewallApp->put_Name(bstrName);    

pIFirewallApps->Add(pIFirewallApp);
 
7.判断一个端口是否被阻止
 
INetFwOpenPorts* pIFirewallOpenPorts = NULL;    
INetFwOpenPort * pIFirewallOpenPort        = NULL;    

m_pIFirewall->get_GloballyOpenPorts(&pIFirewallOpenPorts);    

pIFirewallOpenPorts->Item(lnPort,eProtocolType,&pIFirewallOpenPort);    
VARIANT_BOOL varbEnabled ;    
pIFirewallOpenPort->get_Enabled(&varbEnabled);
 
8. 解除一个端口的阻止
INetFwOpenPorts* pIFirewallOpenPorts = NULL;    
INetFwOpenPort * pIFirewallOpenPort        = NULL;    

m_pIFirewall->get_GloballyOpenPorts(&pIFirewallOpenPorts);    

CoCreateInstance(__uuidof(NetFwOpenPort),NULL,CLSCTX_INPROC_SERVER,    
                    __uuidof(INetFwOpenPort),(void**)&pIFirewallOpenPort);    

pIFirewallOpenPort->put_Port(lnPort);    
pIFirewallOpenPort->put_Protocol(eProtocolType);    
pIFirewallOpenPort->put_Name(bstrShowName);    

pIFirewallOpenPorts->Add(pIFirewallOpenPort);
 
9. 详细代码见附件
 

你可能感兴趣的:(windows,职场,com,休闲,firewall )