.NET Tip: Testing Network Services with the TcpClient Class

Testing whether a server is up and running isn’t very useful when you already know it is. A more useful type of test is verifying that a service is up and running. This applies mostly to non-web services, since web services can be tested using a different class, such as HttpWebRequest. For services such as FTP and SMTP/POP3 mail, you can use the TcpClient class to test whether these services are up and running and responding properly. The TcpClient class is located in the System.Net.Sockets library, so make sure you have that library referenced in your code.

The following example checks two mail servers to make sure they are responding properly:

ArrayList addrs = new ArrayList();
addrs.Add("mail.northcomp.com");
addrs.Add("mail2.northcomp.com");
addrs.Add("mail3.northcomp.com");

byte[] returnBuffer;
foreach (string s in addrs)
{
   TcpClient c = new TcpClient();
   try
   {
      c.Connect(s, 25);
      NetworkStream ns = c.GetStream();
      if (ns.CanRead)
      {
         returnBuffer = new byte[c.ReceiveBufferSize];
         int bytesRead = ns.Read(returnBuffer, 0,
                                 (int)c.ReceiveBufferSize);
         Console.WriteLine("Result from {0}:", s);
         Console.WriteLine(Encoding.UTF8.GetString
                           (returnBuffer).Substring(0, bytesRead));
         ns.Close();
      }
      c.Close();
   }
   catch (Exception ex)
   {
      Console.WriteLine("Error connecting to {0}.", s);
      Console.WriteLine("Exception:");
      Console.WriteLine(ex.ToString());
   }
}

Console.WriteLine("Mail server check completed.");

This code first creates a TcpClient and then attempts to connect to the hostname in question on port 25, which is the default SMTP port. It checks to make sure that the NetworkStream can read data, and if so, it puts that return data into a buffer. The result of the Read method states exactly how many bytes were read, so you can use that value to trim the buffer and eliminate a bunch of empty space at the end. The buffer has to be encoded for display using the Encoding.UTF8.GetString method; otherwise, the data would not display properly.

In this example, the first two addresses will work, but the third one will not. In case of an error, a simple exception trap dumps out the error to the console window. If successful, the example dumps out the text that was received from the server in question. Each of these cases connects to the SMTP port and will get an appropriate greeting from the server. To use this more efficiently, you could look for a particular piece of text in the response to verify that the server was sending the correct response.

You can easily change this code to read the hosts from a database and use other ports, such as FTP, POP3, and so forth. You just need to change the value sent on the Connect method to control which port is being used for the connection.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic. Send him your questions and feedback via e-mail at questions@techniquescentral.com.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read