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.mzph.cn/news/656783.shtml

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

相关文章

分布式定时任务系列9:XXL-job源码分析之路由策略

传送门 分布式定时任务系列1:XXL-job安装 分布式定时任务系列2:XXL-job使用 分布式定时任务系列3:任务执行引擎设计 分布式定时任务系列4:任务执行引擎设计续 分布式定时任务系列5:XXL-job中blockingQueue的应用 …

刘润-底层逻辑 阅读笔记

序言 在面临变化的时候,底层逻辑能够应用到新的变化里面,从而产生新的方法论 从本质上来说,二者都是流量、转化率、客单价和复购率四部分的不同组合 只有不同之中的相同之处、变化背后不变的东西,才是底层逻辑。 底层逻辑环境…

Docker部署Plik系统并结合内网穿透实现远程访问本地上传下载文件

文章目录 1. Docker部署Plik2. 本地访问Plik3. Linux安装Cpolar4. 配置Plik公网地址5. 远程访问Plik6. 固定Plik公网地址7. 固定地址访问Plik 本文介绍如何使用Linux docker方式快速安装Plik并且结合Cpolar内网穿透工具实现远程访问,实现随时随地在任意设备上传或者…

基于springboot原创歌曲分享平台源码和论文

随着信息技术和网络技术的飞速发展,人类已进入全新信息化时代,传统管理技术已无法高效,便捷地管理信息。为了迎合时代需求,优化管理效率,各种各样的管理平台应运而生,各行各业相继进入信息管理时代&#xf…

STM32的GPIO的详细配置指南

1. GPIO简介 GPIO(General Purpose Input/Output)是用于在微控制器中与外部世界通信的接口。通过GPIO,微控制器可以控制外部设备(如LED、LCD、按键等)的状态,也可以接收外部设备的状态(如传感器…

掌握使用 React 和 Ant Design 的个人博客艺术之美

文章目录 前言在React的海洋中起航安装 Create React App安装Ant Design 打造个性化的博客风格通过路由实现多页面美化与样式定制部署与分享总结 前言 在当今数字时代,个人博客成为表达观点、分享经验和展示技能的独特平台。在这个互联网浪潮中,选择使用…

Unity 状态模式(实例详解)

文章目录 简介示例1:基础角色状态切换示例2:添加更多角色状态示例3:战斗状态示例4:动画同步状态示例5:状态机管理器示例6:状态间转换的条件触发示例7:多态行为与上下文类 简介 Unity 中的状态模…

【算法题】79. 单词搜索

题目 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或…

el-input 显示最大长度和已输入内容长度

效果如下图 多行文本框&#xff1a; 单行文本框&#xff1a; 需要设置 maxlength 和 show-word-limit 两个属性&#xff0c;在使用 maxlength 属性限制最大输入长度的同时&#xff0c;可通过设置 show-word-limit 属性来展示字数统计。 <el-inputtype"textarea&quo…

《HTML 简易速速上手小册》第6章:HTML 语义与结构(2024 最新版)

文章目录 6.1 语义化标签的重要性6.1.1 基础知识6.1.2 案例 1&#xff1a;使用 <article>, <section>, <aside>, <header>, 和 <footer>6.1.3 案例 2&#xff1a;构建带有嵌套语义化标签的新闻网站6.1.4 案例 3&#xff1a;创建一个带有 <mai…

SSD寻址单元IU对寿命的影响有多大?

随着存储技术的不断进步&#xff0c;固态硬盘SSD的容量正以惊人的速度增长&#xff0c;尤其是采用高密度QLC NAND闪存技术的大容量SSD&#xff0c;如30TB及以上级别的产品。QLC NAND由于每个单元能够存储4比特数据&#xff0c;从而显著提高了存储密度&#xff0c;但同时也带来了…

纯html+css+js静态汽车商城

首页代码 <!DOCTYPE html> <html class"no-js" lang"zxx"><head><meta charset"utf-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport" content&qu…

学会用Python分割、合并字符串

在很多情况下&#xff0c;我们需要对字符串进行分割或合并&#xff0c;以满足特定的需求&#xff0c;例如将字符串拆分成多个部分、将多个字符串合并成一个等等。Python提供了多种方法来进行字符串的分割和合并&#xff0c;本文将介绍其中几种常用的方法。 一、使用split()函数…

Vue-43、Vue中组件自定义事件

1、给学生绑定atguigu事件 2、在组件内触发事件 第二种写法 传多个参数。 解绑 解绑一个事件 解绑多个自定义事件 this.$off([xxx1,xxx2]);解绑所有事件 this.$off();总结

IDEA Java常用快捷键

目录 main方法快捷键&#xff1a;psvm输出语句&#xff1a;sout复制行&#xff1a;ctrld删除行&#xff1a;ctrly单行注释或多行注释 &#xff1a; Ctrl / 或 Ctrl Shift /for循环 直接 &#xff1a;fori代码块包围&#xff1a;try-catch,if,while等 ctrlaltt缩进&#xff1…

MBA十日读--经营经济学章节 笔记

第7天 经营 解决问题的方法大都取决于调动雇员的积极性 对每一个分解后的工作做进一步研究&#xff0c;可以找到完成它的最有效途径。如果将这些最有效的关键因素结合在一起&#xff0c;就能找到效率最高的生产方法 泰勒本人认为&#xf…

四、防御保护---防火墙NAT篇

四、防御保护---防火墙NAT篇 一、源NAT二、目标NAT三、双向NAT四、多出口NAT 一、源NAT 源NAT — 基于源IP地址进行转换。我们之前接触过的静态NAT&#xff0c;动态NAT&#xff0c;NAPT都属于源NAT&#xff0c;都是针对源IP地址进行转换的。源NAT主要目的是为了保证内网用户可…

SpringBoot-基础

SpringBoot-基础 1.IOC控制反转 Spring的核心是IoC&#xff08;Inversion of Control&#xff0c;控制反转&#xff09;容器&#xff0c;它可以管理容器内的普通Java对象以及对象之间关系的绑定&#xff08;Dependency Injection依赖注入&#xff09;。容器中被管理的对象称为…

基于Javassist字节码增强实现本地公参传递

这里是weihubeats,觉得文章不错可以关注公众号小奏技术&#xff0c;文章首发。拒绝营销号&#xff0c;拒绝标题党 背景 测试线上的公参是通过skywalking agent的方式进行传递的。 如果是本地则会因为获取不到公参报错影响正常测试。所以需要本地也进行公参传递 正常链路是 前…

一体化设计:兼容多种OS系统Linux网关楼宇DDC

在工业物联网&#xff08;IIoT&#xff09;和智能建筑领域&#xff0c;钡铼网关具备高度灵活性与强大计算能力的边缘网关产品正逐渐成为推动行业智能化转型的关键要素。本文将详细介绍的基于Linux系统的4G工业智能网关&#xff0c;不仅拥有NXP i.MX8M Mini四核64位处理器的强大…