{"record":{"id":"c7c12f5ca301db0c","repo":"BornToBeRoot/NETworkManager","slug":"error-while-retrieving-tcp-table","errorCode":null,"errorMessage":"Error while retrieving TCP table","messagePattern":"Error while retrieving TCP table","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"Source/NETworkManager.Models/Network/Connection.cs","lineNumber":87,"sourceCode":"        return Task.Run(GetActiveTcpConnections);\n    }\n\n    private static List<ConnectionInfo> GetActiveTcpConnections()\n    {\n        var result = new List<ConnectionInfo>();\n\n        var size = 0;\n        // ReSharper disable once RedundantAssignment - size is get by reference\n        var dwResult = GetExtendedTcpTable(IntPtr.Zero, ref size, false, 2, TcpTableClass.TCP_TABLE_OWNER_PID_ALL, 0);\n\n        var tcpTable = Marshal.AllocHGlobal(size);\n\n        try\n        {\n            dwResult = GetExtendedTcpTable(tcpTable, ref size, false, 2, TcpTableClass.TCP_TABLE_OWNER_PID_ALL, 0);\n\n            if (dwResult != 0)\n                throw new Exception(\"Error while retrieving TCP table\");\n\n            var tableRows = Marshal.ReadInt32(tcpTable);\n            var rowPtr = tcpTable + 4;\n\n            for (var i = 0; i < tableRows; i++)\n            {\n                var row = (MibTcpRowOwnerPid)Marshal.PtrToStructure(rowPtr, typeof(MibTcpRowOwnerPid))!;\n\n                var localAddress = new IPAddress(row.localAddr);\n                var localPort = BitConverter.ToUInt16([row.localPort2, row.localPort1], 0);\n                var remoteAddress = new IPAddress(row.remoteAddr);\n                var remotePort = BitConverter.ToUInt16([row.remotePort2, row.remotePort1], 0);\n                var state = (TcpState)row.state;\n\n                // Get process info by PID\n                var processId = (int)row.owningPid;\n                var processName = \"-/-\";\n                var processPath = \"-/-\";","sourceCodeStart":69,"sourceCodeEnd":105,"githubUrl":"https://github.com/BornToBeRoot/NETworkManager/blob/2780d65469917a296dbc15f206107d72e2d0115c/Source/NETworkManager.Models/Network/Connection.cs#L69-L105","documentation":"GetActiveTcpConnections calls the Win32 GetExtendedTcpTable API (TCP_TABLE_OWNER_PID_ALL). If the native call returns a non-zero result code (e.g. ERROR_INSUFFICIENT_BUFFER because the table grew, or ERROR_NO_DATA / access issues), the method throws a bare Exception('Error while retrieving TCP table') without exposing the underlying Win32 error code.","triggerScenarios":"Calling GetActiveTcpConnections when the retry loop with the fixed initial buffer cannot satisfy GetExtendedTcpTable (table changed between size query and call), the buffer cannot be allocated, or the API returns ERROR_NO_DATA because there are no TCP connections.","commonSituations":"Rapid connection churn on busy systems causing the size race; systems with very large TCP tables; restricted environments where the API is denied; calling during heavy network changes.","solutions":["Retry GetActiveTcpConnections; the transient size race usually resolves on the next call.","Check the last Win32 error (Marshal.GetLastWin32Error) around the native call for the specific cause.","Increase the initial buffer size or loop with a larger allocation before giving up.","Catch the exception and degrade gracefully (show an empty/unknown connection list) instead of crashing."],"exampleFix":"// before\ndwResult = GetExtendedTcpTable(tcpTable, ref size, false, 2, TcpTableClass.TCP_TABLE_OWNER_PID_ALL, 0);\nif (dwResult != 0)\n    throw new Exception(\"Error while retrieving TCP table\");\n// after\ndwResult = GetExtendedTcpTable(tcpTable, ref size, false, 2, TcpTableClass.TCP_TABLE_OWNER_PID_ALL, 0);\nif (dwResult != 0)\n    throw new Win32Exception((int)dwResult, $\"Error while retrieving TCP table (0x{(uint)dwResult:X})\");","handlingStrategy":"retry","validationCode":"// cannot pre-validate the native table; check environment instead\n// ensure there is at least one active TCP-capable interface\nbool hasNetwork = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();","typeGuard":"null","tryCatchPattern":"try\n{\n    var conns = Connection.GetActiveTcpConnections();\n}\ncatch (Exception ex) when (ex.Message == \"Error while retrieving TCP table\")\n{\n    Log.Warn(\"TCP table unavailable, retrying once...\", ex);\n    await Task.Delay(100);\n    // retry or degrade to empty list\n}","preventionTips":["Retry once on failure; the buffer-size race is transient.","Surface Marshal.GetLastWin32Error for diagnostics when the throw happens.","Never hard-crash the UI for snapshot APIs; degrade to 'unknown'."],"tags":["p-invoke","tcp","windows","network"],"backgroundTag":"api-request-failed","analyzedSha":"2780d65469917a296dbc15f206107d72e2d0115c","analyzedAt":"2026-09-12T17:00:17.986Z","contentChangedAt":"2026-09-12T17:00:17.986Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}