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 occurred
      Type 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;
        else
          return 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;
        else
          return 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;
        else
          return 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 checking
      if (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 checking
      if (!IsFirewallInstalled)
        throw new FirewallHelperException("Cannot grant authorization: Firewall is not installed.");
      if (!AppAuthorizationsAllowed)
        throw new FirewallHelperException("Application exemptions are not allowed.");
      #endregion

      if (!HasAuthorization(applicationFullPath))
      {
        // Get the type of HNetCfg.FwMgr, or null if an error occurred
        Type 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 application
        fwMgr.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 checking
      if (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 checking
      if (!IsFirewallInstalled)
        throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");
      #endregion

      if (HasAuthorization(applicationFullPath))
      {
        // Remove Authorization for this application
        fwMgr.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 checking
      if (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 checking
      if (!IsFirewallInstalled)
        throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");

      #endregion

      // Locate Authorization for this application
      foreach (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 checking
      if (!IsFirewallInstalled)
        throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");

      ArrayList list = new ArrayList();
      //  Collect the paths of all authorized applications
      foreach (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)
    { }
  }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/355685.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

雅特力AT32 Workbench图形化代码生成工具,简化嵌入式开发利器

嵌入式系统应用市场广泛,早已遍及日常生活,随着产品需求复杂度的提升,32位MCU开发难度也随之增加,如何降低开发成本,缩短开发周期,是所有嵌入式开发人员的共同课题。 面对市场竞争日益加剧的情形&#xff…

【Web前端实操17】导航栏效果——滑动门

滑动门 定义: 类似于这种: 滑到导航栏的某一项就会出现相应的画面,里面有对应的画面出现。 箭头图标操作和引用: 像一些图标,如果需要的话,可以找字体图标,比如阿里巴巴矢量图标库:iconfont-阿里巴巴矢量图标库 选择一个——>添加至购物车——>下载代码 因…

实战 | OpenCV+OCR实现弧形文字识别实例(详细步骤 + 源码)

导 读 本文主要介绍基于OpenCV+OCR实现弧形文字识别实例,并给详细步骤和代码。源码在文末。 背景介绍 测试图如下,目标是正确识别图中的字符。图片来源: https://www.51halcon.com/forum.php?mod=viewthread&tid=6712 同样,论坛中已经给出了Halcon实现代码,…

Linux文件管理(下)

上上篇介绍了Linux文件管理的上部分内容,这次继续将 Linux文件管理的剩余部分说完。内容如下。 一、查看文件内容 1、cat 命令 1.1 输出文件内容 基本语法: cat 文件名称主要功能:正序输出文件的内容。 eg:输出 readme.txt文…

《幻兽帕鲁》1月29日游戏服务器推荐!腾讯云降低规格再次降价!

腾讯29日刷新规格,从14M降低到12M,硬盘和流量都有降低,但价格打下来了!价格从66元/月降低到32元/月,277元/3个月降低到96元/3个月! 三大厂商4核16G的云服务器价格对齐,不过具体参数略有不同 阿里…

w24文件上传之PHP伪协议

PHP支持的伪协议 file:// - 访问本地文件系统 http:// - 访问网址 ftp:// - 访问文件 php:// -访问各个输入/输出流 zlib:// -压缩流 data:// - 数据 glob:// -查找匹配的文件路径模式 phar:// - php归档 ssh2:// - Secure shell 2 rar:// - RAR ogg:// - 音频流 expect:// - …

力扣(LeetCode)227. 基本计算器 II

给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。 整数除法仅保留整数部分。 你可以假设给定的表达式总是有效的。所有中间结果将在 [-231, 231 - 1] 的范围内。 注意:不允许使用任何将字符串作为数学表达式计算的内置函数&#…

还能这样学Linux内核,非我族类!

哈喽,我是子牙,一个很卷的硬核男人。深入研究计算机底层、Windows内核、Linux内核、Hotspot源码……聚焦做那些大家想学没地方学的课程 今天的互联网江湖,受大环境影响,已经不似前些年那般朝气蓬勃,裁员严重&#xff…

C#简单使用Yolov5的Onnx格式模型进行目标检测

背景 最近要离职了,同事需要了解一下C#如何使用yolov5系列onnx格式模型进行目标检测,由于其对C#不熟练,可能会影响公司后续的开发进度,所以趁着还在,赶紧把手尾搞好。 方案 1、创建一个C# DotNet 8 控制台项目[可千…

Phoncent博客GPT写作工具

对于许多人来说,写作并不是一件轻松的事情。有时候,我们可能会遇到写作灵感枯竭、写作思路混乱、语言表达困难等问题。为了解决这些问题,Phoncent博客推出了一款创新的工具——GPT写作工具,它利用了GPT技术,为用户提供…

EasyCVR视频智能监管系统方案设计与应用

随着科技的发展,视频监控平台在各个领域的应用越来越广泛。然而,当前的视频监控平台仍存在一些问题,如视频质量不高、监控范围有限、智能化程度不够等。这些问题不仅影响了监控效果,也制约了视频监控平台的发展。 为了解决这些问…

Kafka-服务端-GroupMetadataManager

GroupMetadataManager是GroupCoordinator中负责管理Consumer Group元数据以及其对应offset信息的组件。 GroupMetadataManager底层使用Offsets Topic,以消息的形式存储Consumer Group的GroupMetadata信息以及其消费的每个分区的offset,如图所示。 consumer_offsets的某Partiti…

解决ESP32板载WS2812B LED反色问题及工作状态灯的应用

本文主要介绍使用.Net nanoFramework驱动驱动 ESP32-S3-Zero 板载的 WS2812B LED的问题,以及如何设计一个灯光控制类,来方便的使用工作状态灯来显示设备的工作状态。 1. 引言 在使用Net nanoFramework驱动 ESP32-S3-Zero 的板载 WS2812B LED 时&#xf…

OpenDataLab 大模型训练数据集下载记录

1、访问网站:OpenDataLab 引领AI大模型时代的开放数据平台 (操作之前需要先注册登录) 2、点击数据类型,点击某个数据集进入,会看到数据集的各种详细信息如下图: 3、点击cli下载,第一次进入点击…

每日一题——LeetCode1365.有多少小于当前数字的数字

方法一 暴力循环 对于数组里的没一个元素都遍历一遍看有多少元素小于当前元素 var smallerNumbersThanCurrent function(nums) {let n nums.length;let ret [];for (let i 0; i < n; i) {let count 0;for (let j 0; j < n; j) {if (nums[j] < nums[i]) {count…

Docker 安装与基本操作

目录 一、Docker 概述 1、Docker 简述 2、Docker 的优势 3、Docker与虚拟机的区别 4、Docker 的核心概念 1&#xff09;镜像 2&#xff09;容器 3&#xff09;仓库 二、Docker 安装 1、命令&#xff1a; 2、实操&#xff1a; 三、Docker 镜像操作 1、命令&#xff1…

【算法与数据结构】139、LeetCode单词拆分

文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析&#xff1a;本题可以看做一个动态规划问题。其中&#xff0c;字符串s是背包&#xff0c;而字典中的单词就是物品。…

如何使用Docker部署WBO白板并实现公网地址远程访问

本文主要是如何使用Docker部署WBO白板并实现公网地址远程访问的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是青衿&#x1f947; ☁️博客首页&#xff1a;CSDN主页放风讲故事 &#x1f304;每日一句&am…

AcWing 895. 最长上升子序列(DP序列模型)

[题目概述] 给定一个长度为 N 的数列&#xff0c;求数值严格单调递增的子序列的长度最长是多少。 输入格式 第一行包含整数 N。 第二行包含 N 个整数&#xff0c;表示完整序列。 输出格式 输出一个整数&#xff0c;表示最大长度。 数据范围 1 ≤ N ≤ 1000 &#xff0c; …

《HTML 简易速速上手小册》第1章:HTML 入门(2024 最新版)

文章目录 1.1 HTML 简介与历史&#xff08;&#x1f609;&#x1f310;&#x1f47d;踏上神奇的网页编程之旅&#xff09;1.1.1 从过去到现在的华丽蜕变1.1.2 市场需求 —— HTML的黄金时代1.1.3 企业中的实际应用 —— 不只是个网页1.1.4 职业前景 —— 未来属于你 1.2 基本 H…