尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

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

【转载】  在windows系统中关闭全局socket连接,可跨进程实现“断网”
📅 发布时间:2026/6/20 21:38:33

原文链接: 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;
}

}`

相关新闻

  • 告别“养死”魔咒!AI+知识库+物联网,打造零失败智能种植系统(附架构图+实操指南)
  • 欧姆龙Modbus RTU主站通讯:无协议模式,两步轻松实现
  • 使用是德DSOX1204A快速捕捉与调试信号的技巧

最新新闻

  • Claude Code 接入 DeepSeek V4 的中转层协议转换实战
  • 2026年6月最新浪琴中国官方售后客服服务地址热线网点电话 - 浪琴服务中心
  • 2026年上城区奢侈品包包洗护修复保养,深耕奢护精工 15 载!杭州奢护你贸易扎根雷小安潮奢大厦,以无痕修复传承匠人手艺,打造养护、二创、回收、学徒培训综合产业平台 - GrowthUME
  • 全职太太离婚可以要求补偿吗:3种法定补偿情形与主张要点 - 品牌2026
  • 西安搬家价格全解析:收费标准、一口价与避坑指南,彻底告别隐形收费 - 资讯速览
  • HITAG µ RFID芯片命令解析与CRC-16校验实战指南

日新闻

  • Visual C++运行库修复终极指南:5分钟快速解决Windows软件启动错误
  • 手把手教你构建统计局地区经济数据爬虫:从环境搭建到数据持久化全指南
  • 2026多Agent深度解析:用AI团队替代单一模型,四种架构实战落地

周新闻

  • Visual C++运行库修复终极指南:5分钟快速解决Windows软件启动错误
  • 手把手教你构建统计局地区经济数据爬虫:从环境搭建到数据持久化全指南
  • 2026多Agent深度解析:用AI团队替代单一模型,四种架构实战落地

月新闻

  • 【总结】入门篇:50句话让你记住架构核心概念
  • WeChatMsg技术方案解析:实现Mac微信数据自主管理的完整解决方案
  • WeChatMsg:革新性微信数据备份方案,打造你的专属数字记忆库

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号