欧美成人精品手机在线观看_69视频国产_动漫精品第一页_日韩中文字幕网 - 日本欧美一区二区

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

[點晴永久免費OA]C#實現netstat的功能獲取所有連接到本機的外部IP地址及端口

admin
2022年11月17日 10:5 本文熱度 1359

核心思想是調用 WinAPI 中的 GetExtendedTcpTable 方法來獲取所有活動的 TCP 連接的信息,包括進程ID等等,主要實現如下:

TcpConnectionTableHelper.cs:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace TcpConnectionMonitor
  8. {
  9. public class TcpConnectionTableHelper
  10. {
  11. [DllImport("Ws2_32.dll")]
  12. static extern ushort ntohs(ushort netshort);
  13. [DllImport("iphlpapi.dll", SetLastError = true)]
  14. static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, int ipVersion, TCP_TABLE_TYPE tblClass, int reserved);
  15. [StructLayout(LayoutKind.Sequential)]
  16. public struct MIB_TCPROW_OWNER_PID
  17. {
  18. public uint state;
  19. public uint localAddr;
  20. public byte localPort1;
  21. public byte localPort2;
  22. public byte localPort3;
  23. public byte localPort4;
  24. public uint remoteAddr;
  25. public byte remotePort1;
  26. public byte remotePort2;
  27. public byte remotePort3;
  28. public byte remotePort4;
  29. public int owningPid;
  30. public ushort LocalPort
  31. {
  32. get
  33. {
  34. return BitConverter.ToUInt16(new byte[2] { localPort2, localPort1 }, 0);
  35. }
  36. }
  37. public ushort RemotePort
  38. {
  39. get
  40. {
  41. return BitConverter.ToUInt16(new byte[2] { remotePort2, remotePort1 }, 0);
  42. }
  43. }
  44. }
  45. [StructLayout(LayoutKind.Sequential)]
  46. public struct MIB_TCPTABLE_OWNER_PID
  47. {
  48. public uint dwNumEntries;
  49. MIB_TCPROW_OWNER_PID table;
  50. }
  51. public static string GetIpAddress(long ipAddrs)
  52. {
  53. try
  54. {
  55. System.Net.IPAddress ipAddress = new System.Net.IPAddress(ipAddrs);
  56. return ipAddress.ToString();
  57. }
  58. catch { return ipAddrs.ToString(); }
  59. }
  60. public static ushort GetTcpPort(int tcpPort)
  61. {
  62. return ntohs((ushort)tcpPort);
  63. }
  64. public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
  65. {
  66. MIB_TCPROW_OWNER_PID[] tcpConnectionRows;
  67. int AF_INET = 2; // IPv4
  68. int buffSize = 0;
  69. // use WinAPI GetExtendedTcpTable to query all active tcp connection information
  70. uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_TYPE.TCP_TABLE_OWNER_PID_ALL, 0);
  71. if (ret != 0 && ret != 122) // 122 means insufficient buffer size
  72. {
  73. throw new Exception("Error occurred when trying to query tcp table, return code: " + ret);
  74. }
  75. IntPtr buffTable = Marshal.AllocHGlobal(buffSize);
  76. try
  77. {
  78. ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_TYPE.TCP_TABLE_OWNER_PID_ALL, 0);
  79. if (ret != 0)
  80. {
  81. throw new Exception("Error occurred when trying to query tcp table, return code: " + ret);
  82. }
  83. // get the number of entries in the table
  84. MIB_TCPTABLE_OWNER_PID table = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
  85. IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(table.dwNumEntries));
  86. tcpConnectionRows = new MIB_TCPROW_OWNER_PID[table.dwNumEntries];
  87. for (int i = 0; i < table.dwNumEntries; i++)
  88. {
  89. MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
  90. tcpConnectionRows[i] = tcpRow;
  91. rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
  92. }
  93. }
  94. finally
  95. {
  96. // free memory
  97. Marshal.FreeHGlobal(buffTable);
  98. }
  99. return tcpConnectionRows;
  100. }
  101. }
  102. }
  103. public enum TCP_TABLE_TYPE : int
  104. {
  105. TCP_TABLE_BASIC_LISTENER,
  106. TCP_TABLE_BASIC_CONNECTIONS,
  107. TCP_TABLE_BASIC_ALL,
  108. TCP_TABLE_OWNER_PID_LISTENER,
  109. TCP_TABLE_OWNER_PID_CONNECTIONS,
  110. TCP_TABLE_OWNER_PID_ALL,
  111. TCP_TABLE_OWNER_MODULE_LISTENER,
  112. TCP_TABLE_OWNER_MODULE_CONNECTIONS,
  113. TCP_TABLE_OWNER_MODULE_ALL
  114. }
  115. public enum TCP_CONNECTION_STATE : int
  116. {
  117. CLOSED = 1,
  118. LISTENING,
  119. SYN_SENT,
  120. SYN_RCVD,
  121. ESTABLISHED,
  122. FIN_WAIT_1,
  123. FIN_WAIT_2,
  124. CLOSE_WAIT,
  125. CLOSING,
  126. LAST_ACK,
  127. TIME_WAIT,
  128. delete_TCP
  129. };


Program.cs:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace TcpConnectionMonitor
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. MonitorTcpConnections();
  14. }
  15. static void MonitorTcpConnections()
  16. {
  17. Console.WriteLine("Proto Local Address Foreign Address State PID");
  18. List<String> rows = new List<string>();
  19. while (true)
  20. {
  21. int windowTop = Console.WindowTop; //in order to keep console scroll bar stay
  22. TcpConnectionTableHelper.MIB_TCPROW_OWNER_PID[] tcpProgressInfoTable = TcpConnectionTableHelper.GetAllTcpConnections();
  23. int tableRowCount = tcpProgressInfoTable.Length;
  24. for (int i = 0; i < tableRowCount; i++)
  25. {
  26. TcpConnectionTableHelper.MIB_TCPROW_OWNER_PID row = tcpProgressInfoTable[i];
  27. string source = string.Format("{0}:{1}", TcpConnectionTableHelper.GetIpAddress(row.localAddr), row.LocalPort);
  28. string dest = string.Format("{0}:{1}", TcpConnectionTableHelper.GetIpAddress(row.remoteAddr), row.RemotePort);
  29. string outputRow = string.Format("{0, -7}{1, -23}{2, -23}{3, -16}{4}", "TCP", source, dest, (TCP_CONNECTION_STATE)row.state, row.owningPid);
  30. if (rows.Count < i + 1)
  31. {
  32. Console.SetCursorPosition(0, i + 1);
  33. Console.WriteLine("{0, -80}", outputRow);
  34. rows.Add(outputRow);
  35. }
  36. else if (rows[i] != outputRow)
  37. {
  38. rows[i] = outputRow;
  39. Console.SetCursorPosition(0, i + 1);
  40. Console.WriteLine("{0, -80}", outputRow);
  41. }
  42. }
  43. if (rows.Count > tableRowCount)
  44. {
  45. int linesToBeCleared = rows.Count - tableRowCount;
  46. rows.RemoveRange(tableRowCount, linesToBeCleared);
  47. for (int i = 0; i < linesToBeCleared + 1; i++)
  48. {
  49. Console.WriteLine("{0, -80}", " ");
  50. }
  51. }
  52. Console.SetWindowPosition(0, windowTop); //in order to keep console scroll bar stay
  53. Thread.Sleep(100);
  54. }
  55. }
  56. }
  57. }

實現的效果是每 100ms 獲取一次活躍 TCP 連接的狀態,也就是說每秒大概會刷新10次,為了避免由于刷新頻率過快導致閃爍的問題,通過調用 Console.SetCursorPosition 來對變化的數據進行部分刷新,同時為了避免滾動條存在時,Console 指針引起滾動條自動滾動到最后一行,使用 SetWindowPosition 來固定滾動條的位置。

輸出結果舉例:



該文章在 2022/11/17 10:05:16 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved