我有一个基本的.NET应用程序,我是为公共图书馆编写的,只是启用和禁用互联网访问。它通过切换防火墙并利用UAC来提示管理员凭据来实现此目的。
它运行良好,但它不会关闭现有连接。例如,Facebook Messenger保持连接打开,并在启用防火墙并阻止所有互联网访问后很长时间内继续工作。
理想情况下,我想关闭本地子网外部的所有连接。如果这不可能,关闭端口80/443上的所有连接也会起作用。我想避免必须杀死打开这些连接的实际进程,而宁愿只是自己杀死连接。
我如何实现这一目标?
答案 0 :(得分:0)
我知道这不是你想要的具体你可能会强行使用网络适配器。重新启用后,它将允许您的防火墙规则启动
基本上,没有适配器不能上网
<小时/> Disable network adapter without WMI
<强>的Netsh 强>
Process.Start("cmd.exe","/c netsh interface set interface 'Local Area Connection' DISABLED")
Disable/enable network adapter using WMI
获取网络地址
public static List<NetworkAdapter> GetAllNetworkAdapter()
{
List<NetworkAdapter> allNetworkAdapter = new List<NetworkAdapter>();
// Manufacturer <> 'Microsoft'to get all none virtual devices.
// Because the AdapterType property will be null if the NetworkAdapter is
// disabled, so we do not use NetworkAdapter = 'Ethernet 802.3' or
// NetworkAdapter = 'Wireless’
string strWQuery = "SELECT DeviceID, ProductName, "
+ "NetEnabled, NetConnectionStatus "
+ "FROM Win32_NetworkAdapter "
+ "WHERE Manufacturer <> 'Microsoft'";
ManagementObjectCollection networkAdapters = WMIOperation.WMIQuery(strWQuery);
foreach (ManagementObject moNetworkAdapter in networkAdapters)
{
try
{
allNetworkAdapter.Add(new NetworkAdapter(
Convert.ToInt32(moNetworkAdapter["DeviceID"].ToString()),
moNetworkAdapter["ProductName"].ToString(),
(Convert.ToBoolean(moNetworkAdapter["NetEnabled"].ToString()))
? (int)EnumNetEnabledStatus.Enabled
: (int)EnumNetEnabledStatus.Disabled,
Convert.ToInt32(moNetworkAdapter["NetConnectionStatus"].ToString()
)));
}
catch (NullReferenceException)
{
// Ignore some other devices (like the bluetooth), that need user
// interaction to enable or disable.
}
}
return allNetworkAdapter;
}
启用停用
public int EnableOrDisableNetworkAdapter(string strOperation)
{
int resultEnableDisableNetworkAdapter = (int)EnumEnableDisableResult.Unknow;
ManagementObject crtNetworkAdapter = new ManagementObject();
string strWQuery = string.Format("SELECT DeviceID, ProductName, "
+ "NetEnabled, NetConnectionStatus "
+ "FROM Win32_NetworkAdapter " + "WHERE DeviceID = {0}", DeviceId);
try
{
ManagementObjectCollection networkAdapters =
WMIOperation.WMIQuery(strWQuery);
foreach (ManagementObject networkAdapter in networkAdapters)
{
crtNetworkAdapter = networkAdapter;
}
crtNetworkAdapter.InvokeMethod(strOperation, null);
Thread.Sleep(500);
while (GetNetEnabled() != ((strOperation.Trim() == "Enable")
? (int)EnumNetEnabledStatus.Enabled
: (int)EnumNetEnabledStatus.Disabled))
{
Thread.Sleep(100);
}
resultEnableDisableNetworkAdapter =
(int)EnumEnableDisableResult.Success;
}
catch (NullReferenceException)
{
// If there is a NullReferenceException, the result of the enable or
// disable network adapter operation will be fail
resultEnableDisableNetworkAdapter = (int)EnumEnableDisableResult.Fail;
}
crtNetworkAdapter.Dispose();
return resultEnableDisableNetworkAdapter;
}