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++) 
                // 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 
            catch (SocketException ex) 
                // Connection failed, add port to list of inactive ports 
                // 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("", 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: 
  Inactive Ports: 

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.


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Anthony Christie, the Chief Marketing Officer for Level Communications, is responsible for customer experience, worldwide marketing and product management. In this informative asset, he shares his insights into why a private network connection to cloud-bases applications is the right decision for your enterprise. Download now to find out more.

  • Complex hybrid environments can make it difficult to track interdependencies, increasing the risk of disrupting critical business services. In this white paper by EMA, you'll learn how application discovery and dependency mapping can help you: Meet granular targets for availability, cost, and time-to-revenue for cloud services. Accelerate mean time to repair (MTTR) while communicating better with stakeholders. Manage even the most complex hybrid environments more efficiently and effectively Understand the …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date