当前位置: 首页 > 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.jsqmd.com/news/106515/

相关文章:

  • 露,大鼠活动记录仪 小动物活动记录仪
  • U-boot 源码结构
  • LCR测试仪温度漂移补偿的解决方案
  • 告别“养死”魔咒!AI+知识库+物联网,打造零失败智能种植系统(附架构图+实操指南)
  • 欧姆龙Modbus RTU主站通讯:无协议模式,两步轻松实现
  • 【原创代码分享】基于TOC(龙卷风-科里奥利力优化算法)-XGBoost的时间序列预测模型【原创代码分享】基于线性回归和XGBoost的混合时间序列分解预测
  • 运维远控工具盘点排名第一:为何大公司都选择选择ToDesk
  • Shopee 验证码解决方案
  • UTP测试系统为家电及智能家居产品打造高效、合规、体验至上的验证体系
  • 使用是德DSOX1204A快速捕捉与调试信号的技巧
  • Java毕设项目:基于SpringBoot的少儿编程在线教育网站设计与开发基于Java的scratch少儿编程学习网站系统的设计与实现(源码+文档,讲解、调试运行,定制等)
  • 基于Springboot+Vue超市仓库管理系统(完整源码+万字论文+答辩PPT)
  • 逃离都市喧嚣,我在燕郊百年梨园里找到了理想中的“一方庭院”
  • 一个赚了16倍的老股民的惨痛反思:原来,我只是个幸存者?
  • 【AI早知道】腾讯混元世界模型1.5上线,小米发布新一代MoE大模型MiMo-V2-Flash,Meta拥抱竞品AI
  • 使用Qt OpenGL开发俄罗斯方块:从零到一实现经典游戏
  • 八)--工具和MCP调用
  • Go语言Panic异常服务崩溃
  • .NET 中各种程序目录获取方法的区别与使用场景
  • C语言指针详解:内存操作的核心利器
  • Java毕设项目:基于JAVA的北京市公交管理系统基于Java+Vue+SpringBoot的北京市公交管理系统(源码+文档,讲解、调试运行,定制等)
  • FreeSWITCH开启silk编码及转码
  • 2025年12月mos管,TrenchMos管,SGTMOS管厂商推荐:聚焦企业综合实力与核心竞争力 - 品牌鉴赏师
  • C++医学图像处理经典ITK库用法详解<三>: 图像配准模块功能
  • 7个有效方法提升YashanDB的查询响应速度
  • 自动化测试维护策略:构建可持续的测试资产
  • 2025年12月新能源车电池续航,大巴车电池续航,磷酸铁锂电池续航公司推荐:行业测评与选择指南 - 品牌鉴赏师
  • Java毕设项目:基于Java的采购管理系统的设计与实现(源码+文档,讲解、调试运行,定制等)
  • 实战前瞻:构建高可用、强实时的 Flutter + OpenHarmony 智慧医疗健康平台
  • 8大关键技术点掌握YashanDB的使用技巧