C# Socket 允许控制台应用通过防火墙

需求:

在代码中将exe添加到防火墙规则中,允许Socket通过

添加库引用

效果:

一键三联

若可用记得点赞·评论·收藏哦,你的支持就是写作的动力。

源地址:

https://gist.github.com/cstrahan/513804

调用代码:

private static void AddToFireWall()
{if (FirewallHelper.Instance.HasAuthorization(Environment.ProcessPath)){Console.WriteLine("有防火墙权限");}else{Console.WriteLine("没有防火墙权限");FirewallHelper.Instance.GrantAuthorization(Environment.ProcessPath, Path.GetFileNameWithoutExtension(Environment.ProcessPath));}
}

源代码:

/// /// Allows basic access to the windows firewall API./// This can be used to add an exception to the windows firewall/// exceptions list, so that our programs can continue to run merrily/// even when nasty windows firewall is running.////// Please note: It is not enforced here, but it might be a good idea/// to actually prompt the user before messing with their firewall settings,/// just as a matter of politeness./// /// /// To allow the installers to authorize idiom products to work through/// the Windows Firewall./// public class FirewallHelper{#region Variables/// /// Hooray! Singleton access./// private static FirewallHelper instance = null;/// /// Interface to the firewall manager COM object/// private INetFwMgr fwMgr = null;#endregion#region Properties/// /// Singleton access to the firewallhelper object./// Threadsafe./// public static FirewallHelper Instance{get{lock (typeof(FirewallHelper)){if (instance == null)instance = new FirewallHelper();return instance;}}}#endregion#region Constructivat0r/// /// Private Constructor.  If this fails, HasFirewall will return/// false;/// private FirewallHelper(){// Get the type of HNetCfg.FwMgr, or null if an error occurredType fwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);// Assume failed.fwMgr = null;if (fwMgrType != null){try{fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType);}// In all other circumnstances, fwMgr is null.catch (ArgumentException) { }catch (NotSupportedException) { }catch (System.Reflection.TargetInvocationException) { }catch (MissingMethodException) { }catch (MethodAccessException) { }catch (MemberAccessException) { }catch (InvalidComObjectException) { }catch (COMException) { }catch (TypeLoadException) { }}}#endregion#region Helper Methods/// /// Gets whether or not the firewall is installed on this computer./// /// public bool IsFirewallInstalled{get{if (fwMgr != null &&fwMgr.LocalPolicy != null &&fwMgr.LocalPolicy.CurrentProfile != null)return true;elsereturn false;}}/// /// Returns whether or not the firewall is enabled./// If the firewall is not installed, this returns false./// public bool IsFirewallEnabled{get{if (IsFirewallInstalled && fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled)return true;elsereturn false;}}/// /// Returns whether or not the firewall allows Application "Exceptions"./// If the firewall is not installed, this returns false./// /// /// Added to allow access to this metho/// public bool AppAuthorizationsAllowed{get{if (IsFirewallInstalled && !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed)return true;elsereturn false;}}/// /// Adds an application to the list of authorized applications./// If the application is already authorized, does nothing./// /// ///         The full path to the application executable.  This cannot///         be blank, and cannot be a relative path./// /// ///         This is the name of the application, purely for display///         puposes in the Microsoft Security Center./// /// ///         When applicationFullPath is null OR///         When appName is null./// /// ///         When applicationFullPath is blank OR///         When appName is blank OR///         applicationFullPath contains invalid path characters OR///         applicationFullPath is not an absolute path/// /// ///         If the firewall is not installed OR///         If the firewall does not allow specific application 'exceptions' OR///         Due to an exception in COM this method could not create the///         necessary COM types/// /// ///         If no file exists at the given applicationFullPath/// public void GrantAuthorization(string applicationFullPath, string appName){#region  Parameter checkingif (applicationFullPath == null)throw new ArgumentNullException("applicationFullPath");if (appName == null)throw new ArgumentNullException("appName");if (applicationFullPath.Trim().Length == 0)throw new ArgumentException("applicationFullPath must not be blank");if (applicationFullPath.Trim().Length == 0)throw new ArgumentException("appName must not be blank");if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)throw new ArgumentException("applicationFullPath must not contain invalid path characters");if (!Path.IsPathRooted(applicationFullPath))throw new ArgumentException("applicationFullPath is not an absolute path");if (!File.Exists(applicationFullPath))throw new FileNotFoundException("File does not exist", applicationFullPath);// State checkingif (!IsFirewallInstalled)throw new FirewallHelperException("Cannot grant authorization: Firewall is not installed.");if (!AppAuthorizationsAllowed)throw new FirewallHelperException("Application exemptions are not allowed.");#endregionif (!HasAuthorization(applicationFullPath)){// Get the type of HNetCfg.FwMgr, or null if an error occurredType authAppType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false);// Assume failed.INetFwAuthorizedApplication appInfo = null;if (authAppType != null){try{appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType);}// In all other circumnstances, appInfo is null.catch (ArgumentException) { }catch (NotSupportedException) { }catch (System.Reflection.TargetInvocationException) { }catch (MissingMethodException) { }catch (MethodAccessException) { }catch (MemberAccessException) { }catch (InvalidComObjectException) { }catch (COMException) { }catch (TypeLoadException) { }}if (appInfo == null)throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance.");appInfo.Name = appName;appInfo.ProcessImageFileName = applicationFullPath;// ...// Use defaults for other properties of the AuthorizedApplication COM object// Authorize this applicationfwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo);}// otherwise it already has authorization so do nothing}/// /// Removes an application to the list of authorized applications./// Note that the specified application must exist or a FileNotFound/// exception will be thrown./// If the specified application exists but does not current have/// authorization, this method will do nothing./// /// ///         The full path to the application executable.  This cannot///         be blank, and cannot be a relative path./// /// ///         When applicationFullPath is null/// /// ///         When applicationFullPath is blank OR///         applicationFullPath contains invalid path characters OR///         applicationFullPath is not an absolute path/// /// ///         If the firewall is not installed./// /// ///         If the specified application does not exist./// public void RemoveAuthorization(string applicationFullPath){#region  Parameter checkingif (applicationFullPath == null)throw new ArgumentNullException("applicationFullPath");if (applicationFullPath.Trim().Length == 0)throw new ArgumentException("applicationFullPath must not be blank");if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)throw new ArgumentException("applicationFullPath must not contain invalid path characters");if (!Path.IsPathRooted(applicationFullPath))throw new ArgumentException("applicationFullPath is not an absolute path");if (!File.Exists(applicationFullPath))throw new FileNotFoundException("File does not exist", applicationFullPath);// State checkingif (!IsFirewallInstalled)throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");#endregionif (HasAuthorization(applicationFullPath)){// Remove Authorization for this applicationfwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath);}// otherwise it does not have authorization so do nothing}/// /// Returns whether an application is in the list of authorized applications./// Note if the file does not exist, this throws a FileNotFound exception./// /// ///         The full path to the application executable.  This cannot///         be blank, and cannot be a relative path./// /// ///         The full path to the application executable.  This cannot///         be blank, and cannot be a relative path./// /// ///         When applicationFullPath is null/// /// ///         When applicationFullPath is blank OR///         applicationFullPath contains invalid path characters OR///         applicationFullPath is not an absolute path/// /// ///         If the firewall is not installed./// /// ///         If the specified application does not exist./// public bool HasAuthorization(string applicationFullPath){#region  Parameter checkingif (applicationFullPath == null)throw new ArgumentNullException("applicationFullPath");if (applicationFullPath.Trim().Length == 0)throw new ArgumentException("applicationFullPath must not be blank");if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)throw new ArgumentException("applicationFullPath must not contain invalid path characters");if (!Path.IsPathRooted(applicationFullPath))throw new ArgumentException("applicationFullPath is not an absolute path");if (!File.Exists(applicationFullPath))throw new FileNotFoundException("File does not exist.", applicationFullPath);// State checkingif (!IsFirewallInstalled)throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");#endregion// Locate Authorization for this applicationforeach (string appName in GetAuthorizedAppPaths()){// Paths on windows file systems are not case sensitive.if (appName.ToLower() == applicationFullPath.ToLower())return true;}// Failed to locate the given app.return false;}/// /// Retrieves a collection of paths to applications that are authorized./// /// /// ///         If the Firewall is not installed.///   public ICollection GetAuthorizedAppPaths(){// State checkingif (!IsFirewallInstalled)throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");ArrayList list = new ArrayList();//  Collect the paths of all authorized applicationsforeach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)list.Add(app.ProcessImageFileName);return list;}#endregion}/// /// Describes a FirewallHelperException./// /// ////// public class FirewallHelperException : System.Exception{/// /// Construct a new FirewallHelperException/// /// public FirewallHelperException(string message): base(message){ }}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/440127.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

idea报错:Cannot resolve symbol ‘springframework‘

说明maven没有配置好或者加载好 解决: 1)File–>Invalidate Caches… 清理缓存,重启idea客户端 然后我这里只进行了第一步就不报错了!!! 如果你依然报错,就继续第二步: 2&…

3、css设置样式总结、节点、节点之间关系、创建元素的方式、BOM

一、css设置样式的方式总结: 对象.style.css属性 对象.className ‘’ 会覆盖原来的类 对象.setAttribut(‘style’,‘css样式’) 对象.setAttribute(‘class’,‘类名’) 对象.style.setProperty(css属性名,css属性值) 对象.style.cssText “css样式表” …

Linux:重定向

Linux:重定向 输出重定向追加重定向输出重定向与追加重定向的本质输入重定向 输出重定向 在Linux中,输出重定向是一种将命令的输出发送到不同位置的方法。通常,执行命令时,输出会显示在终端上。然而,使用输出重定向&a…

[AI]文心一言爆火的同时,ChatGPT带来了这么多的开源项目你了解吗

前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家:https://www.captainbed.cn/z ChatGPT体验地址 文章目录 前言4.5key价格泄漏ChatGPT4.0使用地址ChatGPT正确打开方式最新功能语音助手存档…

Habitat环境学习二:导航任务中的Habitat-sim基础Habitat-sim Basics for Navigation

导航任务在Habitat-sim任务中的实现 官方教程概述重要概念1、Hello World程序1.0.1 基础设置Basic settings1.0.2 模拟器设置Configurations for the simulator1.0.3 创建模拟器实例1.0.4 初始化Agent1.0.5 导航和探索 官方教程 Habitat是一个高效的真实的3D模拟器&#xff0c…

深度学习(7)--卷积神经网络项目详解

一.项目介绍: 用Keras工具包搭建训练自己的一个卷积神经网络(Simple_VGGNet,简单版VGGNet),用来识别猫/狗/羊三种图片。 数据集: 二.卷积神经网络构造 查看API文档 Convolution layers (keras.io)https://keras.io/api/layers/…

某知名乳业集团:夯实软件安全基础,助力乳业数字化创新发展

某知名乳业集团,是中国奶粉行业的先驱,其高品质产品和对“更新鲜、更适合”理念的不懈追求,赢得了市场的广泛认可。近年来,屡创营收奇迹,充分展现出强劲的发展韧性,这背后与集团数字化战略转型密不可分。 代…

浅谈安科瑞电力监控系统的设计与应用-安科瑞 蒋静

摘要:介绍上海东华大学电力监控系统,采用综合保护装置、多功能仪表、变压器温控仪、直流屏,采集配电现场的各种电参量和状态信号。系统采用现场就地组网的方式,组网后通过现场总线通讯并远传至后台,通过安科瑞电力监控…

作业车间调度问题:P还是NP

获取更多资讯,赶快关注上面的公众号吧! 文章目录 基本概念多项式时间指数时间 P问题(多项式问题)NP问题(非确定性多项式问题)暴力穷举法动态规划 P与NP关系:作业车间调度问题是典型的NP难问题 …

信息安全考证攻略

🔥在信息安全领域,拥有相关的证书不仅能提升自己的专业技能,更能为职业生涯增添不少光彩。下面为大家盘点了一些国内外实用的信息安全证书,让你一睹为快! 🌟国内证书(认证机构:中国信…

《Numpy 简易速速上手小册》第5章:Numpy高效计算与广播(2024 最新版)

文章目录 5.1 向量化计算5.1.1 基础知识5.1.2 完整案例:股票数据分析5.1.3 拓展案例 1:多维数组运算5.1.4 拓展案例 2:复杂函数的向量化应用 5.2 广播机制5.2.1 基础知识5.2.2 完整案例:二维数据与一维数据运算5.2.3 拓展案例 1&a…

Electron桌面应用实战:Element UI 导航栏橙色轮廓之谜与Bootstrap样式冲突解决方案

目录 引言 问题现象及排查过程 描述问题 深入探索 查明原因 解决方案与策略探讨 重写样式 禁用 Bootstrap 样式片段 深度定制 Element UI 组件 隔离样式作用域 结语 引言 在基于 Electron 开发桌面应用的过程中,我们可能时常遇到各种意想不到的问题…