Client.connect with DNS lookup

Hi, I’m having trouble getting the TCPClient to connect to a server defined by domain name, as opposed to the ip address. I’m basically copying the example from the docs, but substituting in the Google domain name I am unable to connect. Anyone got any ideas? Thanks! Code below:

TCPClient client;
//byte server[] = { 74, 125, 224, 72 }; // Google

void setup()
{
    pinMode(D7,OUTPUT);         // Turn on the D7 led so we know it's time
  digitalWrite(D7,HIGH);      // to open the Serial Terminal.
  Serial.begin(9600);
  while(!Serial.available())  // Wait here until the user presses ENTER 
    SPARK_WLAN_Loop(); 
  Serial.println("connecting...");
 digitalWrite(D7,LOW);
    
  if (client.connect("www.gooogle.com", 80))
  {
    Serial.println("connected");
    client.println("GET /search?q=unicorn HTTP/1.0");
    client.println();
  }
  else
  {
    Serial.println("connection failed");
  }
}

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

  if (!client.connected())
  {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

I think you need to add a Host: www.google.com header to your HTTP GET request. In the modern world, www.google.com is not one host, but many, many distributed hosts that might serve under many DNS names. So one host might be “www.google.com” but it also might be “www.gmail.com” if you see what I mean.

Here is what I typically use, but there are lots of other libraries and ways to do this:

void sendGetRequest(const char * server, const char * url)
{
    if (myTCP.connect(server, 80)) {
        myTCP.print("GET ");
        myTCP.print(url);
        myTCP.println(" HTTP/1.1");
        myTCP.println("Connection: close");
        myTCP.print("Host: ");
        myTCP.println(server);
        myTCP.println("Accept: text/html, text/plain");
        myTCP.println();
        myTCP.flush();
    } 
}

I put the flush() at the end to flush the receive side since I am not likely to want to read anything before the most recent request, but that is totally optional and just fits my use case.

2 Likes

That does it! Thanks so much for your reply, and especially your explanation of why. It works great now.

2 Likes

I have had issues with an immediate .flush() after everything and added a delay(10) just before the flush and it made the server much happier.

1 Like