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){ }}
相关文章:

C# Socket 允许控制台应用通过防火墙
需求: 在代码中将exe添加到防火墙规则中,允许Socket通过 添加库引用 效果: 一键三联 若可用记得点赞评论收藏哦,你的支持就是写作的动力。 源地址: https://gist.github.com/cstrahan/513804 调用代码: private static void …...
Centos安装mysql/mariadb
1,yum install mysql-apt-config_0.8.12-1_all.deb 似乎后面会有冲突,不建议安装mysql了,直接mariadb吧 2, No such command: uninstall. Please use /usr/bin/yum --help It could be a YUM plugin command, try: "yum install dnf-command(uninstall)" It…...

2024 年, Web 前端开发趋势
希腊哲学家赫拉克利特认为,变化是生命中唯一不变的东西。这句话适用于我们的个人生活、行业和职业领域。 尤其是前端开发领域,新技术、开发趋势、库和框架不断涌现,变化并不陌生。最近发生的一些事件正在改变开发人员构建网站和 Web 应用的方…...

Mysql 插入数据
1 为表的所有字段插入数据 使用基本的INSERT语句插入数据要求指定表名称和插入到新记录中的值。基本语法格式为: INSERT INTO table_name (column_list) VALUES (value_list); 使用INSERT插入数据时,允许列名称列表column_list为空,此时&…...
【每日一题】YACS 473:栈的判断
这是上海计算机学会竞赛 P 473 P473 P473:栈的判断( 2021 2021 2021年 8 8 8月月赛 丙组 T 4 T4 T4)标签:栈题意:给定 n n n个数字,已知这些数字的入栈顺序为 1 , 2 , 3... , n 1,2,3...,n 1,2,3...,n&…...
Python - 整理 MySQL 慢查询日志
在实际的数据库管理和性能优化工作中,MySQL 慢查询日志(slow query log)是一个重要的工具。当系统中的 SQL 查询花费的时间超过阈值时,MySQL 会将这些查询记录在慢查询日志中,方便进行性能分析和调优。 本文将介绍如何…...

Python算法题集_无重复字符的最长子串
本文为Python算法题集之一的代码示例 题目3:无重复字符的最长子串 说明:给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。 示例 1: 输入: s "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "a…...

12.Elasticsearch应用(十二)
Elasticsearch应用(十二) 1.单机ES面临的问题 海量数据存储问题单点故障问题 2.ES集群如何解决上面的问题 海量数据存储解决问题: 将索引库从逻辑上拆分为N个分片(Shard),存储到多个节点单点故障问题&a…...

linux -- 内存管理 -- SLAB分配器
SLAB分配器(slab allocator) SLAB分配器用于小内存空间管理,基本思想是:先利用页面分配器分配出单个或多个连续的物理页面,然后再此基础上将整块页面分割为多个相等的小内存单元,来满足小内存空间分配的需…...

【MySQL】学习如何通过DQL进行数据库数据的条件查询
🌈个人主页: Aileen_0v0 🔥热门专栏: 华为鸿蒙系统学习|计算机网络|数据结构与算法 💫个人格言:“没有罗马,那就自己创造罗马~” #mermaid-svg-63IIm2s5sIhQfsfy {font-family:"trebuchet ms",verdana,arial,sans-serif;font-siz…...
TS:子类型关系
子类型关系 1、概念1.1 里氏替换原则1.2 自反性1.3 传递性 2、顶端类型 和 尾端类型3、字面量类型4、undefined 和 null5、枚举类型6、函数类型6.1 变型6.1.1 协变6.1.2 逆变6.1.3 双变 6.2 函数类型间的子类型关系6.2.1 函数参数数量6.2.2 函数参数类型A、非严格函数类型检查B…...

IDEA插件(MyBatis Log Free)
引言 在Java开发中,MyBatis 是一款广泛使用的持久层框架,它简化了SQL映射并提供了强大的数据访问能力。为了更好地调试和优化MyBatis应用中的SQL语句执行,一款名为 MyBatis Log Free 的 IntelliJ IDEA 插件应运而生。这款插件旨在帮助开发者…...

Redis(八)哨兵机制(sentinel)
文章目录 哨兵机制案例认识异常 哨兵运行流程及选举原理主观下线(Subjectively Down)ODown客观下线(Objectively Down)选举出领导者哨兵选出新master过程 哨兵使用建议 哨兵机制 吹哨人巡查监控后台master主机是否故障,如果故障了根据投票数自动将某一个从库转换为新…...

[数据结构]-哈希
前言 作者:小蜗牛向前冲 名言:我可以接受失败,但我不能接受放弃 如果觉的博主的文章还不错的话,还请点赞,收藏,关注👀支持博主。如果发现有问题的地方欢迎❀大家在评论区指正 本期学习目标&…...

宝塔控制面板配置SSL证书实现网站HTTPS
宝塔安装SSL证书提前申请好SSL证书,如果还没有,先去Gworg里面申请,一般几分钟就可以下来,申请地址:首页-Gworg官方店-淘宝网 一、登录邮箱下载:Gworg证书文件目录 ,都会有以下五个文件夹。宝塔…...
elasticsearch优化总结
参考: https://docs.docker.com/manuals/ Manuals | Docker Docs Run Elasticsearch locally | Elasticsearch Guide [8.12] | Elastic 让你的ES查询性能起飞:Elasticsearch 查询优化攻略“一网打尽” - 知乎...
图论第三天|127. 单词接龙 841.钥匙和房间 463. 岛屿的周长 1971. 寻找图中是否存在路径 684.冗余连接 685.冗余连接II
目录 Leetcode127. 单词接龙Leetcode841.钥匙和房间Leetcode463. 岛屿的周长Leetcode1971. 寻找图中是否存在路径Leetcode684.冗余连接Leetcode685.冗余连接II Leetcode127. 单词接龙 文章链接:代码随想录 题目链接:127. 单词接龙 思路:广搜搜…...
react的高阶函数HOC:
React 的高阶组件(Higher-Order Component,HOC)是一种用于复用组件逻辑的模式。它是一个函数,接收一个组件作为参数,并返回一个新的增强过的组件。 HOC 可以用于实现以下功能: 代码复用:通过将…...

STM32——中断系统和外部中断EXTI
一、中断 1.1中断系统 中断系统是管理和执行中断的逻辑结构; 1.2中断 系统在执行主程序过程中,出现了特定的触发条件(触发源),系统停止执行当前程序,转而去执行中断程序,执行完毕后…...
使用uniApp+vue3+Vite4+pinia+sass技术栈构建微信小程序
使用uniApp的cli模式安装,可以使用vscode开发。不用再单独去下载HBuilderX. 1.基础安装 vue3tsuniapp 方法一: npx degit dcloudio/uni-preset-vue#vite-ts my-vue3-project方法二:可以去uni-preset-vue的vite分支下选择vite-ts直接下载zi…...

K8S认证|CKS题库+答案| 11. AppArmor
目录 11. AppArmor 免费获取并激活 CKA_v1.31_模拟系统 题目 开始操作: 1)、切换集群 2)、切换节点 3)、切换到 apparmor 的目录 4)、执行 apparmor 策略模块 5)、修改 pod 文件 6)、…...

如何在看板中有效管理突发紧急任务
在看板中有效管理突发紧急任务需要:设立专门的紧急任务通道、重新调整任务优先级、保持适度的WIP(Work-in-Progress)弹性、优化任务处理流程、提高团队应对突发情况的敏捷性。其中,设立专门的紧急任务通道尤为重要,这能…...

高等数学(下)题型笔记(八)空间解析几何与向量代数
目录 0 前言 1 向量的点乘 1.1 基本公式 1.2 例题 2 向量的叉乘 2.1 基础知识 2.2 例题 3 空间平面方程 3.1 基础知识 3.2 例题 4 空间直线方程 4.1 基础知识 4.2 例题 5 旋转曲面及其方程 5.1 基础知识 5.2 例题 6 空间曲面的法线与切平面 6.1 基础知识 6.2…...
【C++从零实现Json-Rpc框架】第六弹 —— 服务端模块划分
一、项目背景回顾 前五弹完成了Json-Rpc协议解析、请求处理、客户端调用等基础模块搭建。 本弹重点聚焦于服务端的模块划分与架构设计,提升代码结构的可维护性与扩展性。 二、服务端模块设计目标 高内聚低耦合:各模块职责清晰,便于独立开发…...
基于matlab策略迭代和值迭代法的动态规划
经典的基于策略迭代和值迭代法的动态规划matlab代码,实现机器人的最优运输 Dynamic-Programming-master/Environment.pdf , 104724 Dynamic-Programming-master/README.md , 506 Dynamic-Programming-master/generalizedPolicyIteration.m , 1970 Dynamic-Programm…...

Aspose.PDF 限制绕过方案:Java 字节码技术实战分享(仅供学习)
Aspose.PDF 限制绕过方案:Java 字节码技术实战分享(仅供学习) 一、Aspose.PDF 简介二、说明(⚠️仅供学习与研究使用)三、技术流程总览四、准备工作1. 下载 Jar 包2. Maven 项目依赖配置 五、字节码修改实现代码&#…...

嵌入式学习笔记DAY33(网络编程——TCP)
一、网络架构 C/S (client/server 客户端/服务器):由客户端和服务器端两个部分组成。客户端通常是用户使用的应用程序,负责提供用户界面和交互逻辑 ,接收用户输入,向服务器发送请求,并展示服务…...

【C++进阶篇】智能指针
C内存管理终极指南:智能指针从入门到源码剖析 一. 智能指针1.1 auto_ptr1.2 unique_ptr1.3 shared_ptr1.4 make_shared 二. 原理三. shared_ptr循环引用问题三. 线程安全问题四. 内存泄漏4.1 什么是内存泄漏4.2 危害4.3 避免内存泄漏 五. 最后 一. 智能指针 智能指…...
WebRTC从入门到实践 - 零基础教程
WebRTC从入门到实践 - 零基础教程 目录 WebRTC简介 基础概念 工作原理 开发环境搭建 基础实践 三个实战案例 常见问题解答 1. WebRTC简介 1.1 什么是WebRTC? WebRTC(Web Real-Time Communication)是一个支持网页浏览器进行实时语音…...

通过 Ansible 在 Windows 2022 上安装 IIS Web 服务器
拓扑结构 这是一个用于通过 Ansible 部署 IIS Web 服务器的实验室拓扑。 前提条件: 在被管理的节点上安装WinRm 准备一张自签名的证书 开放防火墙入站tcp 5985 5986端口 准备自签名证书 PS C:\Users\azureuser> $cert New-SelfSignedCertificate -DnsName &…...