private IDictionary _ParsePortToProcessMap()

in src/library/Connect/PortMappingManager.cs [177:225]


        private IDictionary<int, int> _ParsePortToProcessMap(string output)
        {
            var result = new Dictionary<int, int>();
            using (StringReader reader = new StringReader(output))
            {
                int currentProcessId = -1;
                int currentPort = 0;
                while (true)
                {
                    var line = reader.ReadLine();

                    // Entire output has been processed
                    if (line == null)
                    {
                        break;
                    }

                    line = line.Trim();
                    var parts = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length > 1 && parts[0].StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
                    {
                        // 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))
                        {
                            // Yes, this port is bound on all IPs.
                            if (int.TryParse(localAddress.Substring(localAddress.LastIndexOf(':') + 1), out int port) && port > 0 && port < 65536
                                && int.TryParse(parts.Last(), out int processId) && processId > 0)
                            {
                                currentPort = port;
                                currentProcessId = processId;
                            }
                        }
                    }

                    // Add the last port and process ID details that were read.
                    // If port details have been already added or not yet determined, currentPort value is 0.
                    if (currentPort > 0)
                    {
                        result[currentPort] = currentProcessId;
                        currentPort = 0;
                    }
                }
            }

            return result;
        }