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

【转载】 在windows系统中关闭全局socket连接,可跨进程实现“断网”

原文链接: how-do-i-close-a-socket-ipv4-and-ipv6-connection-on-windows-from-any-process

c# 代码
`using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

// add 2.0.0 version as nuget package
using DigitalRuby.IPBanCore;

namespace YourNamespace;

///


/// Socket closer interface
///

public interface ISocketCloser
{
///
/// Close a socket using low level windows API. Handles ipv4 and ipv6.
///

/// Local end point
/// Remote end point
/// True if closed, false if not
bool CloseSocket(IPEndPoint local, IPEndPoint remote);
}

///


/// Close sockets on Windows or Linux
///

public partial class SocketCloser : ISocketCloser
{
private const int MIB_TCP_STATE_DELETE_TCB = 12;

private static readonly byte[] moduleId = [0x18, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x4A, 0x00, 0xEB, 0x1A, 0x9B, 0xD4, 0x11, 0x91, 0x23, 0x00, 0x50, 0x04, 0x77, 0x59, 0xBC];
private static readonly IntPtr moduleIdPtr;[LibraryImport("iphlpapi.dll", SetLastError = true)]
private static partial uint SetTcpEntry(ref MIB_TCPROW pTcpRow);[LibraryImport("nsi.dll", SetLastError = true)]
private static partial uint NsiSetAllParameters(uint action, uint flags, IntPtr moduleId, uint operation, IntPtr buffer, uint bufferLength, IntPtr metric, uint metricLength);[StructLayout(LayoutKind.Sequential)]
private struct MIB_TCPROW
{public uint dwState;public uint dwLocalAddr;public uint dwLocalPort;public uint dwRemoteAddr;public uint dwRemotePort;
}[StructLayout(LayoutKind.Sequential)]
private struct KillTcpSocketData_V6
{public ushort wLocalAddressFamily;public ushort wLocalPort;public uint bReserved1;[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]public byte[] bLocal;public uint dwLocalScopeID;public ushort wRemoteAddressFamily;public ushort wRemotePort;public uint bReserved2;[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]public byte[] bRemote;public uint dwRemoteScopeID;
};static SocketCloser()
{moduleIdPtr = Marshal.AllocHGlobal(moduleId.Length);Marshal.Copy(moduleId, 0, moduleIdPtr, moduleId.Length);
}/// <inheritdoc />
public bool CloseSocket(IPEndPoint local, IPEndPoint remote)
{if (OSUtility.IsLinux){return CloseSocketLinux(local, remote);}else if (OSUtility.IsWindows){return CloseSocketWindows(local, remote);}return false;
}private static bool CloseSocketLinux(IPEndPoint local, IPEndPoint remote)
{// sudo ss --kill state all src IP_ADDRESS:PORT dst IP_ADDRESS:PORTstring command = $"ss --kill state all src \"{local.Address}:{local.Port}\" dst \"{remote.Address}:{remote.Port}\"";OSUtility.StartProcessAndWait("sudo", command, 0);return true;
}
private static bool CloseSocketWindows(IPEndPoint local, IPEndPoint remote)
{var localPortFixed = (ushort)IPAddress.HostToNetworkOrder((short)local.Port);var remotePortFixed = (ushort)IPAddress.HostToNetworkOrder((short)remote.Port);if (local.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork){MIB_TCPROW row = new(){dwState = MIB_TCP_STATE_DELETE_TCB,dwLocalAddr = local.Address.ToUInt32(false),dwLocalPort = (uint)localPortFixed,dwRemoteAddr = remote.Address.ToUInt32(false),dwRemotePort = (uint)remotePortFixed};var result = SetTcpEntry(ref row);return result == 0 || result == 317;}else if (local.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6){KillTcpSocketData_V6 row6 = new(){wLocalAddressFamily = (ushort)AddressFamily.InterNetworkV6,wLocalPort = localPortFixed,bLocal = local.Address.GetAddressBytes(),bRemote = remote.Address.GetAddressBytes(),bReserved1 = 0,bReserved2 = 0,dwLocalScopeID = (uint)IPAddress.HostToNetworkOrder(local.Address.ScopeId),dwRemoteScopeID = (uint)IPAddress.HostToNetworkOrder(remote.Address.ScopeId),wRemoteAddressFamily = (ushort)AddressFamily.InterNetworkV6,wRemotePort = remotePortFixed};// Assume global module ID and other parameters are correctly setvar ptrSize = Marshal.SizeOf<KillTcpSocketData_V6>();var ptr = Marshal.AllocHGlobal(ptrSize);try{// Call the undocumented API (the values for module ID, etc., must be correct)Marshal.StructureToPtr(row6, ptr, false);var result = NsiSetAllParameters(1, 2, moduleIdPtr, 16, ptr, (uint)ptrSize, IntPtr.Zero, 0);return result == 0 || result == 317;}finally{// CleanupMarshal.FreeHGlobal(ptr);}}return false;
}

}`

http://www.rkmt.cn/news/117560.html

相关文章:

  • 告别“养死”魔咒!AI+知识库+物联网,打造零失败智能种植系统(附架构图+实操指南)
  • 欧姆龙Modbus RTU主站通讯:无协议模式,两步轻松实现
  • 使用是德DSOX1204A快速捕捉与调试信号的技巧
  • Shopee 验证码解决方案
  • 【AI早知道】腾讯混元世界模型1.5上线,小米发布新一代MoE大模型MiMo-V2-Flash,Meta拥抱竞品AI
  • 2025年12月广口全自动吹瓶机,手插式自动吹瓶机,半自动吹瓶机模具公司推荐:行业测评与选择指南 - 品牌鉴赏师
  • 2025年12月TrenchMos管,SGTMOS管,SuperJunctionMos管公司推荐:行业测评与选择指南 - 品牌鉴赏师
  • llama.cpp Server 引入路由模式:多模型热切换与进程隔离机制详解
  • 【学习心得】Python好库推荐——pyttsx3
  • Java毕设项目:基于javaweb的学生管理系统(源码+文档,讲解、调试运行,定制等)
  • AspectJ、Spring AOP 与 Solon AOP:Java AOP 框架的三剑客
  • Qt共享内存疑难解析:从创建失败到完美解决
  • 大语言模型从零到一:理论基础全解析,助你快速掌握LLM核心技术与构建方法!
  • Kubernetes Service 架构深度解析:从虚拟IP到流量的智能寻址
  • 2特殊单字符和空白符
  • 自动化测试投资回报率(ROI)分析与实践指南
  • 什么叫组团社,什么叫地接社
  • 安徽做SCARA机器人的公司有哪些?
  • 自动化测试与手工测试的平衡之道:构建高效质量保障体系
  • 基于SpringBoot+Vue汽车维修保养服务信息系统(完整源码+万字论文+精品PPT)
  • 用 Canvas 实现《黑客帝国》代码雨:自适应 120Hz、发光特效、音频与鼠标交互
  • 自动化测试的7个误区:从业者必知陷阱与规避策略
  • Qwen3模型vLLM并行配置性能测试:从0.6B到32B的最佳实践指南!
  • 软件测试外包管理的精细化实施框架
  • 【C++ 笔记】从 C 到 C++:核心过渡 (中)
  • 【机器学习】4.XGBoost(Extreme Gradient Boosting)
  • 通过算法备案之后就万事大吉了么?
  • 每日八股——Go(4)
  • QtC++定时3秒执行槽函数实战
  • 自动化运维利器Ansible