.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.



Comments

  • labelDisplayText

    Posted by jame on 03/31/2007 11:23am

    I get an error when Visual Web Developer 2005 Express Edition runs the code. The error I get is Compiler Error Message: CS0103: The name 'labelDisplayText' does not exist in the current context. Does any one know what to use instead?

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

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Today's "average" business in general is ever more reliant on technology and the Internet. Mobility is the most often cited business trend that has transformed the way many of us work and communicate. From an IT security perspective, this means that protection methods and tools from even a few years ago are rapidly becoming "unfit for purpose." This guide provides crucial facts to assist you in building a robust business case, meeting the demands of your business, and protecting against threats now and in the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds