TcpTable.cs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. using System;
  2. using System.Buffers.Binary;
  3. using System.Diagnostics;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Runtime.InteropServices;
  7. using System.Runtime.Versioning;
  8. namespace FastGithub.ReverseProxy
  9. {
  10. /// <summary>
  11. /// windows iphlpapi
  12. /// </summary>
  13. [SupportedOSPlatform("windows")]
  14. unsafe static class TcpTable
  15. {
  16. private const int ERROR_INSUFFICIENT_BUFFER = 122;
  17. [DllImport("iphlpapi.dll", SetLastError = true)]
  18. private static extern uint GetExtendedTcpTable(void* pTcpTable, ref int pdwSize, bool bOrder, AddressFamily ulAf, TCP_TABLE_CLASS tableClass, uint reserved = 0);
  19. /// <summary>
  20. /// 杀死占用进程
  21. /// </summary>
  22. /// <param name="port"></param>
  23. /// <returns></returns>
  24. public static bool KillPortOwner(int port)
  25. {
  26. if (TryGetOwnerProcessId(port, out var pid) == false)
  27. {
  28. return true;
  29. }
  30. try
  31. {
  32. var proess = Process.GetProcessById(pid);
  33. proess.Kill();
  34. return proess.WaitForExit(1000);
  35. }
  36. catch (ArgumentException)
  37. {
  38. return true;
  39. }
  40. catch (Exception)
  41. {
  42. return false;
  43. }
  44. }
  45. /// <summary>
  46. /// 获取tcp端口的占用进程id
  47. /// </summary>
  48. /// <param name="port"></param>
  49. /// <param name="processId"></param>
  50. /// <returns></returns>
  51. public static bool TryGetOwnerProcessId(int port, out int processId)
  52. {
  53. processId = 0;
  54. var pdwSize = 0;
  55. var result = GetExtendedTcpTable(null, ref pdwSize, false, AddressFamily.InterNetwork, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_LISTENER);
  56. if (result != ERROR_INSUFFICIENT_BUFFER)
  57. {
  58. return false;
  59. }
  60. var buffer = new byte[pdwSize];
  61. fixed (byte* pTcpTable = &buffer[0])
  62. {
  63. result = GetExtendedTcpTable(pTcpTable, ref pdwSize, false, AddressFamily.InterNetwork, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_LISTENER);
  64. if (result != 0)
  65. {
  66. return false;
  67. }
  68. var prt = new IntPtr(pTcpTable);
  69. var table = Marshal.PtrToStructure<MIB_TCPTABLE_OWNER_PID>(prt);
  70. prt += sizeof(int);
  71. for (var i = 0; i < table.dwNumEntries; i++)
  72. {
  73. var row = Marshal.PtrToStructure<MIB_TCPROW_OWNER_PID>(prt);
  74. if (row.LocalPort == port)
  75. {
  76. processId = row.ProcessId;
  77. return true;
  78. }
  79. prt += Marshal.SizeOf<MIB_TCPROW_OWNER_PID>();
  80. }
  81. }
  82. return false;
  83. }
  84. private enum TCP_TABLE_CLASS
  85. {
  86. TCP_TABLE_BASIC_LISTENER,
  87. TCP_TABLE_BASIC_CONNECTIONS,
  88. TCP_TABLE_BASIC_ALL,
  89. TCP_TABLE_OWNER_PID_LISTENER,
  90. TCP_TABLE_OWNER_PID_CONNECTIONS,
  91. TCP_TABLE_OWNER_PID_ALL,
  92. TCP_TABLE_OWNER_MODULE_LISTENER,
  93. TCP_TABLE_OWNER_MODULE_CONNECTIONS,
  94. TCP_TABLE_OWNER_MODULE_ALL
  95. }
  96. [StructLayout(LayoutKind.Sequential)]
  97. private struct MIB_TCPTABLE_OWNER_PID
  98. {
  99. public uint dwNumEntries;
  100. }
  101. [StructLayout(LayoutKind.Sequential)]
  102. private struct MIB_TCPROW_OWNER_PID
  103. {
  104. public uint state;
  105. public uint localAddr;
  106. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
  107. public byte[] localPort;
  108. public uint remoteAddr;
  109. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
  110. public byte[] remotePort;
  111. public int owningPid;
  112. public int ProcessId => owningPid;
  113. public IPAddress LocalAddress => new(localAddr);
  114. public ushort LocalPort => BinaryPrimitives.ReadUInt16BigEndian(this.localPort);
  115. }
  116. }
  117. }