Problem on Ethernet library client.read()

I am using the Ethernet shield (W5100) with arduino-0022.

I am trying to run a very simple TCP server on arduino, but I get a lot of strange/unwanted characters when I use the fucntion client.read().

The code is this one:

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

// network configuration.  gateway and subnet are optional.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 0, 220 };


// telnet defaults to port 23
Server server(23);

void setup()
{
  // initialize the ethernet device
  Serial.begin(9600);
  Ethernet.begin(mac, ip);

  // start listening for clients
  server.begin();
}

void loop()
{
  Client client = server.available();
  if (client) {
    client.print(client.read());
  }
}

I connect from my computer (gnu/linux) using telnet. As soon as I connect, I see a lot of numbers coming out:

telnet 192.168.0.220
Trying 192.168.0.220...
Connected to 192.168.0.220.
Escape character is '^]'.
2552533255251242552513125525132255251332552513425525139255253525525135979797979797979797979797979713101221221221221221221221310979797979797979797979797979797979797979797979797979797979797979797979797979797109898989898989898989898989898989898989898989898989898101010989898989898989898989898989898989898989898989898989898989898101421949999229742320242425891281...

I made many experiments and it seems that the client.read() function continuously read the input buffer, without discarding the read bytes. The sequence of bytes read is cyclical. After a while, it restart to print the same number.

It seems like a bug in the Ethernet library.

Does anybody have the same problem?

It seems like a bug in the Ethernet library.

There's a bug, alright. But, it isn't in the Ethernet library.

Where are you checking that the client actually has something to read? Use client.available() BEFORE calling client.read(), or, at the very least, assure that client.read() returned something useful before you try to print it.

Actually I also tried using client.available() before client.read(), but it does not work.

On arduino-0018, client.read() hangs.
On arduino-0022, client.read() returns a character, even thou no characters were sent to the server.

Anyway I could finally solve this problem by using the arduino-0018 and the Ethernet2 library:

http://code.google.com/p/tinkerit/source/browse/#svn%2Ftrunk%2FEthernet2%20library%2FEthernet2%253Fstate%253Dclosed

I attach the Ethernet2 library, ready to be installed and used on arduino-0018.

Ethernet2.tar.gz (31.6 KB)