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,一经查实,立即删除!

相关文章

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 中的状态模…

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…

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

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

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

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

《golang设计模式》第三部分·行为型模式-10-模板方法(Template Method)

文章目录 1. 概述1.1 角色1.2 类图 2. 代码示例2.1 设计2.2 代码2.3 类图 1. 概述 模板方法&#xff08;Template Method&#xff09;用来定义算法的框架&#xff0c;将算法中的可变步骤定义为抽象方法&#xff0c;指定子类实现或重写。 1.1 角色 AbstractClass&#xff08;…

Kettle-Docker部署+Sqlserver数据同步Mysql+Start定时任务

一. 背景介绍 1. ETL是什么 ETL&#xff08;Extract-Transform-Load&#xff09;&#xff0c;即数据抽取、转换、装载的过程。它是一种思想&#xff0c;主要是说&#xff0c;从不同的数据源获取数据&#xff0c;并通过对数据进行处理&#xff08;格式&#xff0c;协议等转换&a…

第32关 k8s集群管理开源神器 - k9s

------> 课程视频同步分享在今日头条和B站 大家好&#xff0c;我是博哥爱运维。 随着我们管理维护的K8S集群上线&#xff0c;怎么管理好集群上面成百上千的服务pod&#xff0c;就是我们该操心的事情了。这里博哥把在生产中一直在用的一个开源管理工具k8s&#xff0c;github…

Jenkins如何从GIT下拉项目并启动Tomcat

一、先添加服务器 二、添加视图 点击控制台输出&#xff0c;滑到最下面&#xff0c;出现这个就说明构建成功了&#xff0c;如果没有出现&#xff0c;说明构建有问题&#xff0c;需要解决好问题才能启动哦~

C++实现通讯录管理系统

目录 1、系统需求 2、创建项目 2.1 创建项目 3、菜单功能 4、退出功能 5、添加联系人 5.1 设计联系人结构体 5.2 设计通讯录结构体 5.3 main函数中创建通讯录 5.4 封装联系人函数 5.5 测试添加联系人功能 6、显示联系人 6.1 封装显示联系人函数 7、删除联系人 7.1…

GPT栏目:yarn 安装

GPT栏目&#xff1a;yarn 安装 一、前言 在跟GPT交互的时候&#xff0c;发现最近gpt4给出的答案率有了比较明显的提高&#xff0c;简单记录一下&#xff0c;我用gpt4拿到的答案吧。 本人已按照这个步骤成功 二、具体步骤 要安装 yarn&#xff0c;你可以按照以下步骤进行操作…