C# - Port scanner

1

I tried to make port scanner but for some reason, it doesn't work good:

Proxy List:

138.68.169.8

My Code:

    private static string IP = "";

    static void Main(string[] args)
    {
        UserInput();
        PortScan();
        Console.ReadKey();
    }

    private static void UserInput()
    {
        Console.WriteLine("IP Address:", Color.Lime);
        IP = Console.ReadLine();
    }

    private static void PortScan()
    {
        Console.Clear();
        TcpClient Scan = new TcpClient();
        foreach(int s in Ports)
        {
            try
            {
                Scan.Connect(IP, s);
                Console.WriteLine($"[{s}] | OPEN", Color.Green);
            }
            catch
            {
                Console.WriteLine($"[{s}] | CLOSED", Color.Red);
            }
        }
    }

    private static int[] Ports = new int[]
    {
        8080,
        51372,
        31146,
        4145
    };

Exception:

[8080] | OPEN
[51372] | CLOSEDSystem.Net.Sockets.SocketException (0x80004005): A connect request was made on an already connected socket

The other ports have the same exceptions.

Why did it say open ports when the proxy:port is different?

c#
proxy
port
asked on Stack Overflow Sep 29, 2018 by Daniel • edited Sep 29, 2018 by Daniel

1 Answer

0

A connect request was made on an already connected socket

The error message means that you have already established a connection, and that you're trying to establish another connection using the same client. You should close the first connection before opening another.

I would move the TcpClient into a using block within your loop so that the connection is closed and the client is disposed between connection attempts:

foreach(int s in Ports)
{
    using (TcpClient Scan = new TcpClient())
    {
        try
        {
            Scan.Connect(IP, s);
            Console.WriteLine($"[{s}] | OPEN", Color.Green);
        }
        catch
        {
            Console.WriteLine($"[{s}] | CLOSED", Color.Red);
        }
    }
}
answered on Stack Overflow Sep 29, 2018 by Llama

User contributions licensed under CC BY-SA 3.0