Testing for a Valid HTTP Server in Java

| 1 Comment

I’m currently writing a diagnostics tool to perform all the same connectivity diagnostic checks that I do manually when I am having trouble connecting to something.  The following code snippet is how I am checking to see if a web or proxy server is listening on a particular port.  I thought I’d post a similar example here in case it was useful to you.

    public String pingHttp(String host, int port) throws Exception
    {
        PrintWriter output;
        InputStream input;
        StringBuffer response = new StringBuffer();
        try
        {
            Socket httpSocket = new Socket(host, port);
            // Timeout after 5 seconds of trying to talk over socket.
            httpSocket.setSoTimeout(5000);
            output = new PrintWriter(httpSocket.getOutputStream(), false);
            input = httpSocket.getInputStream();
            output.print("OPTIONS * HTTP/1.1\nHost: " + host + "\nUser-Agent: Woodwardweb.com Diagnostics\r\n\r\n");
            output.flush();
            
            // Read maximum of 1k of data as we don't really care what this says.
            byte[] b = new byte[1024];
            int n = input.read(b);
            response.append(new String(b, 0, n));
            output.close();
            input.close();
            httpSocket.close();
            
        }
        catch (UnknownHostException e)
        {
            throw new Exception("Could not resolve the host \"" + host + "\"",e);
        }
        catch (SocketTimeoutException e)
        {
            throw new Exception("The host \"" + host + "\" did not respond in a timely manner");
        }
        catch (IOException e)
        {
            throw new Exception("Could not connect to port " + port +" on \"" + host + "\"",e);
        }
        return response.toString();
    }

Note that the OPTIONS http method is very useful as a ping or noop type call on a web server.  Some web server administrators (such as Google) deny the OPTIONS request as it isn’t something that you’ll see a browser doing and they want to minimise their attack surface for the naughty folks out there in internet land.  Even if they do, you will still get some http response back (i.e. a String beginning with “HTTP”) which you can test for to tell if a web server exists on that port.

1 Comment

I wrote a similar thing a while ago that ran on a thread and tested my webhost's webserver periodically. I amassed a bunch of data showing their server's uptime and downtime. I was constantly complaining that my site was down often, and they claimed it was "my code". By showing logs of their server's activity and also logs of the amount of times they restarted their servlet engine, I could prove that not only was it their fault that the server was down, but also that they were lying about how often they restarted the servlet engine.

Archives

Creative Commons License
This blog is licensed under a Creative Commons License.