Search code examples
c#tcpclientuptime-monitoring

TcpClient connecting to unavailable service


So far the code I have is

`tcpClient = new TcpClient();
tcpClient.Connect(ip.IpAddress, Convert.ToInt32(ip.Port));
if (tcpClient.Connected)
{
  Console.WriteLine("Host is up");
  Console.ReadKey();
}
else
{
  UpdateDowntime(ip);
}`

The ipAddress and port I am testing is a DEV site running through IIS. I have stopped the AppPool for this site. If I navigate to this through the browser I get

Service Unavailable

HTTP Error 503. The service is unavailable.

But if I run the code it connects and prints "Host is up"

Please inform what I am missing in the step.


Solution

  • Adding this in case anyone is running into the same problem. This was my solution after using the link in my comment above.

    foreach (var ip in ipAddressList)
    {
        HttpWebResponse myHttpWebResponse = null;
        try
        {
            var myUri = new Uri(ip.Url);
            // Create a 'HttpWebRequest' object for the specified url. 
            var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
            // Set the user agent as if we were a web browser
            myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4";
            myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            // Release resources of response object.
            myHttpWebResponse.Close();
        }
        catch (WebException ex)
        {
            // If we get here, port is not open, or host is not reachable
            UpdateDowntime(ip, ex.Message);
        }
        finally
        {
            if (myHttpWebResponse != null)
            {
                myHttpWebResponse.Close();
            }
        }
    }
    

    Inside UpdateDowntime(), I load service results to the database when the URL was not accessible so this can be reported on and a Task Scheduler task was created to run this every 5 minutes. It also sends an email when a service is down. Tells which service went down, when and what was the response error.

    My end result will be using SSRS to make a report whenever executives need to know metrics on multiple different scenarios of when things went down, for how long, if they were down during prime hours, etc., etc.

    Hope this helps someone else if they find the same issue.