Exercise: Port scanner

In this exercise you must make a program that scans your computer for open TCP and UDP ports.

IMPORTANT: You must scan your own computer (""). It is not legal to scan someone else computer!

TCP and UDP ports are in the range 0 ... 65535 (2^16 = 65536)

You must make a program that finds any open ports on your computer - i.e. any port that has a server attached to it.

TCP port scanning

Console application ...

Basic idea:


Your sequential program probably runs fairly slow. In most cases it tries to make a TCP connection to a host - and then it waits for the connection attempt to time-out. This take quite some time - and you do it 65436 times.

Introduce tasks so that each scan of a particular port is done in a separate task: 1 port = 1 task.

Possible problem: The program should stop when the last port has been scanned - not before, not long after.
Console.ReadLine(...) is Not a suitable way to wait for the program to stop.

The tasks can be created and executed in different ways:

Which one seems to run faster? And why?

The class StopWatch might be helpful in measuring running times:

Which one seems faster to program?


Use Trace.WriteLine (not Console.WriteLine) to report when an open port is found.

Another idea: Use TcpListener, not TcpClient

Until now you make a TcpClient object trying to connect to a possibly existing server.

Another idea is to try to make a TcpListener. If you get an exception there is another server running on the port. If not the port is free.
Don't forget to close your TcpListener object.

Is this faster or slower than using TcpClient? Why?

UDP port scanning

Now you have to do the same for UDP ...

Basic idea:

How fast is this compared to TCP port scanning?

Which servers

Which servers are "hiding" behind the port numbers?

Consult List of TCP and UDP port numbers.