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.



Comments

  • 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

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • VMware vCloud® Government Service provided by Carpathia® is an enterprise-class hybrid cloud service that delivers the tried and tested VMware capabilities widely used by government organizations today, with the added security and compliance assurance of FedRAMP authorization. The hybrid cloud is becoming more and more prevalent – in fact, nearly three-fourths of large enterprises expect to have hybrid deployments by 2015, according to a recent Gartner analyst report. Learn about the benefits of …

Most Popular Programming Stories

More for Developers

RSS Feeds