Are Ports on Your Computers Listening?

Several of the applications I work with on a daily basis use TCP or UDP to
communicate with each other. One application is listening on a specific port,
waiting to receive data from the sending application. Occasionally the receiving
application is not there, ready for the data. The problem could be a power
outage, the network may be unavailable, or there could be a *gasp* bug that has
caused the application not to be available. It would be nice to know this before
the sending application attempts to make a connection so that the problem can be
rectified before it impacts that system.

It is not difficult for you to write an application that scans the ports of
interest and monitors their status. Below is a PortScanner class that you could
use as a skeleton for monitoring your computers. The Scan method takes the IP
address and port range to scan and builds a list of ports within the range that
are active and inactive. A socket is used to attempt to make a TCP connection to
each port in the range. If the connection succeeds the port is added to the
active port list otherwise the port is added to the inactive port list. The list
of ports is accessed through the ActivePorts and InactivePorts member variables.

using System.Collections.Generic;
using System.Net.Sockets;

class PortScanner
{
    public List<int> ActivePorts = new List<int>();
    public List<int> InactivePorts = new List<int>();

    public PortScanner()
    {
    }

    public void Scan(string IP, int StartPort, int EndPort)
    {
        Socket Sock = null;
        for (int Port = StartPort; Port <= EndPort; Port++)
        {
            try
            {
                // Create a new socket and attempt to connect to the ip/port
                Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Sock.Connect(IP, Port);
                // Connection succeeded, add port to list of active ports
                ActivePorts.Add(Port);
            }
            catch (SocketException ex)
            {
                // Connection failed, add port to list of inactive ports
                InactivePorts.Add(Port);
            }
            finally
            {
                // Gracefully close down the socket
                if (Sock != null)
                {
                    if (Sock.Connected)
                        Sock.Disconnect(false); Sock.Close();
                }
            }
        }
    }
} 

Using PortScanner is straightforward. Create an instance of the PortScanner
class and call the Scan method with the IP address and port range you need to
monitor. The code below does just that and then displays the list of active and
inactive ports on the console.

// Create a new PortScanner
PortScanner PS = new PortScanner();

// Scan for open ports
PS.Scan("10.1.1.12", 5995, 5999);

// Write out the list of active/inactive ports
Console.WriteLine("Port Scanner Results:");
Console.WriteLine(" Open Ports: ");
foreach (int Port in PS.OpenPorts)
    Console.WriteLine(" " + Port.ToString());
Console.WriteLine(" Closed Ports: ");
foreach (int Port in PS.ClosedPorts)
    Console.WriteLine(" " + Port.ToString()); 

Here is the console output for this example.

Port Scanner Results:
  Active Ports:
    5999
  Inactive Ports:
    5995
    5996
    5997
    5998   

I said the PortScanner class could be used as a skeleton for you own monitor for
good reason. I've stripped away parts of the class I use to keep the example
simple and short. The ActivePorts and InactivePorts members should really be
private. They could then be exposed through properties that return a read-only
version of the list so that they can't be changed by the application using the
PortScanner class. The Scan method only uses a TCP connection to test the port.
Depending upon your application you may need to use a different protocol.
Additions could be made to the Scan method to determine the reason the
connection failed. You also need to decide what to do with the information you
now have about the ports. I'll leave these items as exercises for you to
complete to make this fit your needs.

I also recommend that you don't just start running this against all the servers
in your organization. First, scanning a wide range of ports is not a very fast
process. Second, you may set off alarms if your servers are monitoring for port
scanners in order to prevent unwanted access.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read