Ethernet, connect(), timeout


based on WebClient example I am trying to connect to my web server. It works as expected, but standard behaviour does not meet my specific need.

Story: Arduino tries to connect to web server to get some data. If it cannot establish connection, it will use data stored in EEPROM or SD card instead. In case of network/web server problem, client.connect() takes more than 30 seconds to return false. I need true or false within 2 seconds.

Question: Is it possible to set timeout period for connect() method?

Thank you


Have you looked at the source code for Client?

I tracked it down to socket.cpp, function connect:

This function established the connection for the channel in Active (client) mode. This function waits for the untill the connection is established.

Then down to :

void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) {
  // Send command to socket
  writeSnCR(s, _cmd);
  // Wait for command to complete
  while (readSnCR(s))

but cannot find writeSnCR neither readSnCR.

you could patch this loop like:

unsigned long limit = to be determined;
unsigned long t = 0;
while (readSnCR(s) && (t < limit) ) t++;

not nice but it might do the trick ?

The troublesome code is not the execCmdSn; that returns instantly. The problem is back in Client::connect()

while (status() != SnSR::ESTABLISHED) {
    if (status() == SnSR::CLOSED) {
      _sock = MAX_SOCK_NUM;
      return 0;

That is where you would put the patch suggested by robtillaart…but, it’s so much easier than that!

The simple fix

arduino-0021\libraries\Ethernet\utility\w5100.cpp, add 2 lines to make the init function look like this

void W5100Class::init(void)



  for (int i=0; i<MAX_SOCK_NUM; i++) {
    SBASE[i] = TXBUF_BASE + SSIZE * i;
    RBASE[i] = RXBUF_BASE + RSIZE * i;

setRetransmissionTime sets the Wiznet’s timeout period, where each unit is 100us, so 0x07D0 (decimal 2000) means 200ms.

setRetransmissionCount sets the Wiznet’s retry count.

A retry count of 2 or 3 makes the connect function fail really quickly.

Hope that helps.



The simpler fix

You don’t even need to modify the library code. In your sketch, add this include:

#include <utility/w5100.h>

then, in your setup, after you call Ethernet.begin(), add the following two lines:


That gives me a 3 second timeout on a bad server connection.

Thanks. I will try this solution soon.