当前位置: 首页 > 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…...

【位运算】消失的两个数字(hard)

消失的两个数字(hard) 题⽬描述:解法(位运算):Java 算法代码:更简便代码 题⽬链接:⾯试题 17.19. 消失的两个数字 题⽬描述: 给定⼀个数组,包含从 1 到 N 所有…...

鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/

使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题:docker pull 失败 网络不同,需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...

NLP学习路线图(二十三):长短期记忆网络(LSTM)

在自然语言处理(NLP)领域,我们时刻面临着处理序列数据的核心挑战。无论是理解句子的结构、分析文本的情感,还是实现语言的翻译,都需要模型能够捕捉词语之间依时序产生的复杂依赖关系。传统的神经网络结构在处理这种序列依赖时显得力不从心,而循环神经网络(RNN) 曾被视为…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)

UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中,UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化&#xf…...

ip子接口配置及删除

配置永久生效的子接口,2个IP 都可以登录你这一台服务器。重启不失效。 永久的 [应用] vi /etc/sysconfig/network-scripts/ifcfg-eth0修改文件内内容 TYPE"Ethernet" BOOTPROTO"none" NAME"eth0" DEVICE"eth0" ONBOOT&q…...

Python 实现 Web 静态服务器(HTTP 协议)

目录 一、在本地启动 HTTP 服务器1. Windows 下安装 node.js1)下载安装包2)配置环境变量3)安装镜像4)node.js 的常用命令 2. 安装 http-server 服务3. 使用 http-server 开启服务1)使用 http-server2)详解 …...

【从零开始学习JVM | 第四篇】类加载器和双亲委派机制(高频面试题)

前言: 双亲委派机制对于面试这块来说非常重要,在实际开发中也是经常遇见需要打破双亲委派的需求,今天我们一起来探索一下什么是双亲委派机制,在此之前我们先介绍一下类的加载器。 目录 ​编辑 前言: 类加载器 1. …...

pycharm 设置环境出错

pycharm 设置环境出错 pycharm 新建项目,设置虚拟环境,出错 pycharm 出错 Cannot open Local Failed to start [powershell.exe, -NoExit, -ExecutionPolicy, Bypass, -File, C:\Program Files\JetBrains\PyCharm 2024.1.3\plugins\terminal\shell-int…...

React从基础入门到高级实战:React 实战项目 - 项目五:微前端与模块化架构

React 实战项目:微前端与模块化架构 欢迎来到 React 开发教程专栏 的第 30 篇!在前 29 篇文章中,我们从 React 的基础概念逐步深入到高级技巧,涵盖了组件设计、状态管理、路由配置、性能优化和企业级应用等核心内容。这一次&…...

LangChain【6】之输出解析器:结构化LLM响应的关键工具

文章目录 一 LangChain输出解析器概述1.1 什么是输出解析器?1.2 主要功能与工作原理1.3 常用解析器类型 二 主要输出解析器类型2.1 Pydantic/Json输出解析器2.2 结构化输出解析器2.3 列表解析器2.4 日期解析器2.5 Json输出解析器2.6 xml输出解析器 三 高级使用技巧3…...