Created
August 4, 2023 02:56
-
-
Save SteveSyfuhs/60d132f3e030c000f2ebdaef61965c35 to your computer and use it in GitHub Desktop.
Finding and killing a socket owner by port
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void KillExistingHosts(int port) | |
{ | |
if (Environment.OSVersion.Platform != PlatformID.Win32NT) | |
{ | |
return; | |
} | |
using (var existing = Win32.FindProcessOwner(port)) | |
{ | |
if (existing == null) | |
{ | |
return; | |
} | |
existing.Kill(entireProcessTree: true); | |
} | |
} | |
private static partial class Win32 | |
{ | |
public static unsafe Process FindProcessOwner(int port) | |
{ | |
uint size = 0; | |
var err = GetTcpTable2(null, &size, false); | |
if (size <= 0) | |
{ | |
throw new Win32Exception((int)err); | |
} | |
Span<byte> tableData = new byte[size]; | |
fixed (byte* tableBytes = &MemoryMarshal.GetReference(tableData)) | |
{ | |
MIB_TCPTABLE2* table = (MIB_TCPTABLE2*)tableBytes; | |
err = GetTcpTable2(table, &size, false); | |
if (err != 0) | |
{ | |
throw new Win32Exception((int)err); | |
} | |
for (var i = 0; i < table->dwNumEntries; i++) | |
{ | |
MIB_TCPROW2* row = &table->table; | |
if (row[i].dwLocalPort == port) | |
{ | |
return Process.GetProcessById(row[i].dwOwningPid); | |
} | |
} | |
} | |
return null; | |
} | |
[LibraryImport("Iphlpapi.dll")] | |
public static unsafe partial uint GetTcpTable2( | |
MIB_TCPTABLE2* table, | |
uint* size, | |
[MarshalAs(UnmanagedType.Bool)] bool order | |
); | |
[StructLayout(LayoutKind.Sequential)] | |
public unsafe struct MIB_TCPTABLE2 | |
{ | |
public int dwNumEntries; | |
public MIB_TCPROW2 table; | |
} | |
[StructLayout(LayoutKind.Sequential)] | |
public struct MIB_TCPROW2 | |
{ | |
public int dwState; | |
public int dwLocalAddr; | |
public int dwLocalPort; | |
public int dwRemoteAddr; | |
public int dwRemotePort; | |
public int dwOwningPid; | |
public int dwOffloadState; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment