Thread: How to multithread my port scanning app?

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    2

    Smile How to multithread my port scanning app?

    I'm creating a small port scanning app which use a port range defined by user.

    My problem with the code is that I find it not efficient enough meaning that it ping very slow, especially when ports are not responding meaning that I must wait for the timeout before continuing to next port.

    I want to make this small app threaded. The problem here is that I'm kind of blank of how to implement threading in my program.

    This is my code which is a method which does the actual checking, the other part of the code is a simple button with for loop for advancing my port number.
    Code:
                    private void ScanPort(IPAddress address, int port)
            {
                using (TcpClient client = new TcpClient())
                {
                    IAsyncResult result = client.BeginConnect(address, port, null, null);
    
                    if (result.AsyncWaitHandle.WaitOne((int)nudTimeout.Value, false)) txtDisplay.AppendText("Port: " + port + " is open." + Environment.NewLine);
                    else txtDisplay.AppendText("Port: " + port + " is closed." + Environment.NewLine);
                }
            }
    I have read some basic threading tutorial but I just don't know how to implement this piece of code so I can check ports much faster.

    Hope for some advices.

    Regards.

  2. #2
    Registered User
    Join Date
    Mar 2009
    Location
    england
    Posts
    209
    You don't need to manually create threads with Async sockets.

  3. #3
    Registered User
    Join Date
    Jan 2012
    Posts
    2
    Quote Originally Posted by theoobe View Post
    You don't need to manually create threads with Async sockets.
    Well, I'm kind of stuck at this part. I have tried to use asynchronous tcp socket connection but I couldn't figure out how to work it out of articles like this or this and my code doesn't do what I would like it to do, to check ports at least much faster speed without wait for single thread to reach the timeout.

  4. #4
    Registered User
    Join Date
    Mar 2011
    Posts
    41
    Replace your for loop with Parallel.For

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To multithread or not ?
    By serge in forum C++ Programming
    Replies: 6
    Last Post: 06-16-2008, 12:15 AM
  2. Again on multithread...
    By BrownB in forum C++ Programming
    Replies: 6
    Last Post: 07-13-2006, 01:58 AM
  3. multithread in 98
    By joecaveman in forum Windows Programming
    Replies: 3
    Last Post: 03-13-2005, 10:41 AM
  4. Port Scanning
    By kryzexy in forum C++ Programming
    Replies: 3
    Last Post: 05-08-2004, 02:48 AM
  5. port scanning
    By HEADSH(+)T in forum C++ Programming
    Replies: 4
    Last Post: 04-23-2004, 02:44 AM

Tags for this Thread