Checking a site [SOLVED]

I am trying to check if a web page is up or not.
Just checking client.connect does not seem to work as it returns true even if the site does not exists.
Actually the best would be to check returned status for 200.
Can someone advice please?

This is the code I have now, that does not work.

char server[] = "google.com";
TCPClient client;

void checkTheSite()
{
    flashGreenLed();
   
    if (client.connect(server, 80))
        digitalWrite(ERRORPIN, LOW);
    else
        digitalWrite(ERRORPIN, HIGH);
           
    client.stop();
}

You can use client.connected() that returns true or false depending on whether the TCP client is connected. Keep in mind that even if the site doesn’t exist, a server may exist at that domain name for the TCP client to connect to.

Here’s a quick sample script:

char server[] = "google.com";
TCPClient client;

void setup() {
    pinMode(D7, OUTPUT);
    Serial.begin(115200);
    digitalWrite(D7, HIGH);
    
    delay(5000);
    
    if (client.connect(server, 80)) {
        client.println("GET / HTTP/1.1");
        client.println("Host: google.com");
        client.println("Content-length: 0");
        client.println();
    }
    
    digitalWrite(D7, LOW);
}

void loop() {
    if (client.available()) {
        char c = client.read();
        Serial.print(c);
    }
    
    if (!client.connected()) {
        client.stop();
    }
}```

The output is:

HTTP/1.1 302 Found
Location: http://www.google.com/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
X-Content-Type-Options: nosniff
Date: Mon, 26 May 2014 15:15:49 GMT
Server: sffe
Content-Length: 219
X-XSS-Protection: 1; mode=block
Alternate-Protocol: 80:quic

302 Moved

302 Moved

The document has moved here. ```

You may be able to parse for “HTTP/1.1 200 OK”. Here’s the method I use to parse for strings in TCP client responses (inside loop()):

    if (client.available()) {
        char c = client.read();
        data.concat(c);
        
        if(data.endsWith("\n")) {
            Serial.println(data);
            
            if(data.indexOf("200 OK")>=0) {
                Serial.println("*** SUCCESS ***");
            } else if(data.indexOf("302 Found")>=0) {
                Serial.println("*** REDIRECT ***");
            }
            
            data = "";
        }
    }```

That way, it waits until the end of a line before parsing and uses `.indexOf()` to see if the substring exists.
1 Like

YES!!! Got it working finally. Thanks for the help. :smiley:

1 Like

Hi @wgbartley, I typed the same code what you posted here and I just get “Connection falided”. What kind of modifications I have to keep in mind? (i.e port number vary from a country or some?) It’s kind of a weird since it should work. Thanks! :smiley: