Ethernet shield fails to connect sometimes

So when i run the code at the bottom, sometimes the arduino fails to connect to the server. Serial output:

connecting...

connection failed
disconnecting.

Sometimes it runs just fine:

connecting...
connected
HTTP/1.1 200 OK
Date: Tue, 28 Jun 2016 14:11:27 GMT
Server: Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.4
Last-Modified: Tue, 28 Jun 2016 14:02:23 GMT
ETag: "8f-5365716136d00"
Accept-Ranges: bytes
Content-Length: 143
Connection: close
Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
The content of the document......
</body>

</html>
disconnecting.

Any idea why this might be happening?

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

char server[] = "192.168.1.100";    // name address for Google (using DNS)

IPAddress ip(192, 168, 0, 177);


EthernetClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
  }


  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Ethernet.begin(mac, ip);
  }

  delay(1000);
  Serial.println("connecting...");

  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /diploma/test.html HTTP/1.1");
    client.println("Host: 192.168.1.100");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

Two things I would change.

  1. Change the server to an IPAddress data type.
// change this
char server[] = "192.168.1.100"; 
// to this
IPAddress server(192,168,1,100);
  1. I would add a Serial.print of the DHCP IP address. Does it show the IP as 192.168.0.177 or something else?
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Ethernet.begin(mac, ip);
  }
  Serial.println(Ethernet.localIP());

The ip address is 192.168.1.101 no matter if it fails or if it succeeds.

Interesting.

I use a 2 second delay between the Ethernet.begin call and attempting a connection. Try increasing your delay from 1 second to two seconds. Don’t know what else to try.