internal IDictionary ParseProcessPortMap()

in src/endpointmanager/System/WindowsSystemCheckService.cs [72:123]


        internal IDictionary<int, string> ParseProcessPortMap(string output)
        {
            var result = new Dictionary<int, string>();
            using (var reader = new StringReader(output))
            {
                string processName = "";
                int currentPort = 0;
                while (true)
                {
                    var line = reader.ReadLine();
                    if (line == null)
                    {
                        if (currentPort > 0)
                        {
                            result[currentPort] = processName;
                        }
                        break;
                    }
                    line = line.Trim();
                    var parts = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length > 1 && parts[0].StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
                    {
                        if (currentPort > 0)
                        {
                            result[currentPort] = processName;
                            currentPort = 0;
                        }
                        // This is the TCP line, such as this:
                        //      TCP    0.0.0.0:80             0.0.0.0:0              LISTENING    1234
                        string localAddress = parts[1];
                        if (localAddress.StartsWith("0.0.0.0:", StringComparison.OrdinalIgnoreCase) ||
                            localAddress.StartsWith("[::]:", StringComparison.OrdinalIgnoreCase))
                        {
                            // We can tell that this port is bound by some process or service on all IPs, so we won't be able to listen on this port regardless of which IP we choose.
                            // If we want to use this port, the service will need to be disabled.
                            int port, processId;
                            if (int.TryParse(localAddress.Substring(localAddress.LastIndexOf(':') + 1), out port) && port > 0 && port < 65536
                                && int.TryParse(parts.Last(), out processId) && processId > 0)
                            {
                                currentPort = port;
                                processName = $"PID {processId}";
                            }
                        }
                    }
                    else if (currentPort > 0)
                    {
                        processName = processName + " " + line;
                    }
                }
            }
            return result;
        }