.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

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds