.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

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

  • "Security" is the number one issue holding business leaders back from the cloud. But does the reality match the perception? Keeping data close to home, on premises, makes business and IT leaders feel inherently more secure. But the truth is, cloud solutions can offer companies real, tangible security advantages. Before you assume that on-site is the only way to keep data safe, it's worth taking a comprehensive approach to evaluating risks. Doing so can lead to big benefits.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds