.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

  • When individual departments procure cloud service for their own use, they usually don't consider the hazardous organization-wide implications. Read this paper to learn best practices for setting up an internal, IT-based cloud brokerage function that service the entire organization. Find out how this approach enables you to retain top-down visibility and control of network security and manage the impact of cloud traffic on your WAN.

  • Live Event Date: September 23, 2015 @ 1:00 p.m. ET / 10:00 a.m. PT The cloud is not just about a runtime platform for your projects – now, you can do your development in the cloud, too. Check out this upcoming eseminar to learn how the cloud improves your development experience and team collaboration. Join Dana Singleterry, Principal Product Manager for Oracle Dev Tools, as he discusses how to simplify every aspect of the development lifecycle, including requirements gathering, version management, code …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date