Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Simple TCP Port Scanner

, 19 May 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Just wrote this to scan for open ports on some software... it's pretty fast!

This entry demonstrates a simple TCP port scanner. 

Note the use of goto statements, which, as any good programmer knows, should be used frequently. (if you think I'm serious, shoot yourself.) 

But really, note the use of the asynchronous methods of BeginConnect and EndConnect on the socket.  This allows me to open a whole load of ports at one time for connections, and then wait for the associated responses instead of doing the work synchronously, which would take too much time. 

Also, understand that the console window that this is running in (it's a console app) is not thread-safe, so any writes to the console from multiple threads are indeterministic, which can cause weird behavior.  So, my solution to this is to lock the console every time I call  PrintWaitingForResponses() or otherwise write to the console. 

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace PortScanner
{
    class Program
    {
        static bool stop = false;
        static int startPort;
        static int endPort;

        static List<int> openPorts = new List<int>();

        static object consoleLock = new object();

        static int waitingForResponses;

        static int maxQueriesAtOneTime = 100;

        static void Main(string[] args)
        {
        begin:
            Console.WriteLine("Enter the IP Address of the target:");
            string ip = Console.ReadLine();

            IPAddress ipAddress;

            if (!IPAddress.TryParse(ip, out ipAddress))
                goto begin;

        startP:

            Console.WriteLine("Enter the starting port to start scanning on:");
            string sp = Console.ReadLine();

            if (!int.TryParse(sp, out startPort))
                goto startP;

        endP:

            Console.WriteLine("Enter the end port:");
            string ep = Console.ReadLine();

            if (!int.TryParse(ep, out endPort))
                goto endP;

            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");

            Console.WriteLine("Press any key to stop scanning...");

            Console.WriteLine("");
            Console.WriteLine("");

            ThreadPool.QueueUserWorkItem(StartScan, ipAddress);

            Console.ReadKey();

            stop = true;

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        static void StartScan(object o)
        {
            IPAddress ipAddress = o as IPAddress;

            for (int i = startPort; i < endPort; i++)
            {
                lock (consoleLock)
                {
                    int top = Console.CursorTop;

                    Console.CursorTop = 7;
                    Console.WriteLine("Scanning port: {0}    ",  i);

                    Console.CursorTop = top;
                }

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

                if (stop)
                    break;                

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

                    s.BeginConnect(new IPEndPoint(ipAddress, i), EndConnect, s);

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

                }
            }
        }

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

                Socket s = ar.AsyncState as Socket;

                s.EndConnect(ar);

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

                    openPorts.Add(openPort);
                    
                    lock (consoleLock)
                    {
                        Console.WriteLine("Connected TCP on port: {0}", openPort);
                    }                

                    s.Disconnect(true);
                }
            }
            catch (Exception)
            {
                
            }
        }

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

            PrintWaitingForResponses();
        }        

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

            PrintWaitingForResponses();
        }

        static void PrintWaitingForResponses()
        {
            lock (consoleLock)
            {
                int top = Console.CursorTop;

                Console.CursorTop = 8;
                Console.WriteLine("Waiting for responses from {0} sockets       ", waitingForResponses);

                Console.CursorTop = top;
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Aron Weiler
Technical Lead CareFusion
United States United States
I just looooove software.
 
Check out my technical blog here: The Fyslexic Duck. You can find most of what I've put on CodeProject there, plus some additional technical articles.

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberteknihacko28-Apr-13 1:17 
GeneralGoto? Pinmemberulfemsoy23-May-11 21:32 
GeneralMy vote of 2 Pinmemberulfemsoy23-May-11 21:29 
GeneralMy vote of 5 PinmemberAron Weiler19-May-11 13:03 
GeneralRe: My vote of 5 PinmemberMember 1017693419-Feb-14 15:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 19 May 2011
Article Copyright 2011 by Aron Weiler
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid