Find out which service is being used on tcp port C #

1

I created a Scan Port in C # (winforms), which is checking a range of ports, previously set, I can verify that the port is open, but my problem is: I know the port is open, but I do not know what kind of service is running on that port, is there a function or library that I can check which service is running on these open ports?

public void StartScan(object o)
{
    IPAddress ipAddress = o as IPAddress;
    gridPortaAberta.Rows.Clear();


    for (int i = startPort; i <= endPort; i++)
    {
        lock (consoleLock)
        {

            label5.Text = "Scaneando Porta: " + i;
        }

        while (waitingForResponses >= maxQueriesAtOneTime)
            Thread.Sleep(0);

        if (stop)
            break;

        try
        {
            Socket s = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.Tcp);


            //Representa um ponto de extremidade de rede como um endereço IP e um número de porta.
            s.BeginConnect(new IPEndPoint(ipAddress, i), EndConnect, s);

            Interlocked.Increment(ref waitingForResponses);
        }
        catch (Exception)
        {

        }
    }
}

public void EndConnect(IAsyncResult ar)
{
    try
    {
        DecrementResponses();

        List<string> items = new List<string>();

        Socket s = ar.AsyncState as Socket;

        s.EndConnect(ar);

        if (s.Connected)
        {
            int openPort = Convert.ToInt32(s.RemoteEndPoint.ToString().Split(':')[1]);

            openPorts.Add(openPort);


            gridPortaAberta.Rows.Add(openPort.ToString());

            lock (consoleLock)
            {
                Console.WriteLine("TCP conectado na porta: { 0}", openPort);
            }

            s.Disconnect(true);
        }

    }
    catch (Exception)
    {

    }
}

public void IncrementResponses()
{
    Interlocked.Increment(ref waitingForResponses);

    PrintWaitingForResponses();
}

public void DecrementResponses()
{
    Interlocked.Decrement(ref waitingForResponses);

    PrintWaitingForResponses();
}

public void PrintWaitingForResponses()
{
    lock (consoleLock)
    {

        label6.Text = "Esperando respostas de " + waitingForResponses + " threads";


    }
}
    
asked by anonymous 13.03.2018 / 22:02

1 answer

1

You can use netstat -b to get this information. You can execute this command with the Process.Start and read the output returned by this to get the process + port pair information. I made a small example.

public class UsedPort
{
    public int Port { get; set; }
    public string Process { get; set; }
}
public static IEnumerable<UsedPort> GetUsedPorts()
{
    var process = Process.Start(new ProcessStartInfo("netstat", "-anb")
    {
        RedirectStandardOutput = true,
        UseShellExecute = false
    });
    string line = null;
    while ((line = process.StandardOutput.ReadLine()) != null)
    {
        if (line.IndexOf("TCP") >= 0 || line.IndexOf("UDP") >= 0)
        {
            var row = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
            var localAddress = row[1];
            var processName = process.StandardOutput.ReadLine();
            if(!processName.Contains("Can not obtain ownership information")){
                yield return new UsedPort
                {
                    Port = int.Parse(localAddress.Split(':').Last()),
                    Process = processName
                };
            }
        }
    }
}
    
14.03.2018 / 10:55