当前位置: 首页 > news >正文

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中断 系统在执行主程序过程中,出现了特定的触发条件(触发源),系统停止执行当前程序,转而去执行中断程序,执行完毕后&#xf…...

使用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…...

Vim 调用外部命令学习笔记

Vim 外部命令集成完全指南 文章目录 Vim 外部命令集成完全指南核心概念理解命令语法解析语法对比 常用外部命令详解文本排序与去重文本筛选与搜索高级 grep 搜索技巧文本替换与编辑字符处理高级文本处理编程语言处理其他实用命令 范围操作示例指定行范围处理复合命令示例 实用技…...

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道(多模态 OCR → 语义检索 → 答案渲染)、两级检索(倒排 BM25 向量 HNSW)并以大语言模型兜底”的整体框架: 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后,分别用…...

【网络】每天掌握一个Linux命令 - iftop

在Linux系统中,iftop是网络管理的得力助手,能实时监控网络流量、连接情况等,帮助排查网络异常。接下来从多方面详细介绍它。 目录 【网络】每天掌握一个Linux命令 - iftop工具概述安装方式核心功能基础用法进阶操作实战案例面试题场景生产场景…...

<6>-MySQL表的增删查改

目录 一,create(创建表) 二,retrieve(查询表) 1,select列 2,where条件 三,update(更新表) 四,delete(删除表&#xf…...

Linux简单的操作

ls ls 查看当前目录 ll 查看详细内容 ls -a 查看所有的内容 ls --help 查看方法文档 pwd pwd 查看当前路径 cd cd 转路径 cd .. 转上一级路径 cd 名 转换路径 …...

【快手拥抱开源】通过快手团队开源的 KwaiCoder-AutoThink-preview 解锁大语言模型的潜力

引言: 在人工智能快速发展的浪潮中,快手Kwaipilot团队推出的 KwaiCoder-AutoThink-preview 具有里程碑意义——这是首个公开的AutoThink大语言模型(LLM)。该模型代表着该领域的重大突破,通过独特方式融合思考与非思考…...

在四层代理中还原真实客户端ngx_stream_realip_module

一、模块原理与价值 PROXY Protocol 回溯 第三方负载均衡(如 HAProxy、AWS NLB、阿里 SLB)发起上游连接时,将真实客户端 IP/Port 写入 PROXY Protocol v1/v2 头。Stream 层接收到头部后,ngx_stream_realip_module 从中提取原始信息…...

React19源码系列之 事件插件系统

事件类别 事件类型 定义 文档 Event Event 接口表示在 EventTarget 上出现的事件。 Event - Web API | MDN UIEvent UIEvent 接口表示简单的用户界面事件。 UIEvent - Web API | MDN KeyboardEvent KeyboardEvent 对象描述了用户与键盘的交互。 KeyboardEvent - Web…...

【Go】3、Go语言进阶与依赖管理

前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课,做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程,它的核心机制是 Goroutine 协程、Channel 通道,并基于CSP(Communicating Sequential Processes&#xff0…...

AI编程--插件对比分析:CodeRider、GitHub Copilot及其他

AI编程插件对比分析:CodeRider、GitHub Copilot及其他 随着人工智能技术的快速发展,AI编程插件已成为提升开发者生产力的重要工具。CodeRider和GitHub Copilot作为市场上的领先者,分别以其独特的特性和生态系统吸引了大量开发者。本文将从功…...