I am trying to make a connection with the EthernetClient, but it always fails with code 0. I decided to write a small code just to test if the client ever becomes ready, and as I suspected it does not.
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {0x2A, 0x27, 0x55, 0x08, 0x1E, 0x6A};
IPAddress ip(172, 16, 48, 133);
EthernetClient client;
void setup() {
Ethernet.init(10);
Ethernet.begin(mac, ip);
Serial.begin(9600);
while (!Serial) {;}
for (auto link = Ethernet.linkStatus(); link != LinkON; link = Ethernet.linkStatus()) {;}
Serial.println("Link ON");
while(!client){
Serial.println("Client not ready");
delay(1000);
}
Serial.println("Client ready!");
}
void loop() {}
If I try to run the code above, it gets stuck at the "Client not ready" loop, and I can't figure it out what I'm missing for it to work.
Obs.: I have already configured a web server with success with my shield, so I'm guessing the problem is not with it.
1 Answer 1
An EthernetClient
expects to connect to a remote socket. At no point do you instruct it to connect to a socket, so it never succeeds.
At some point before checking for a connection you need to initiate that connection:
// arduino.cc is 100.24.172.113
IPAddress server(100, 24, 172, 113);
client.connect(server, 80);
The if (client)
operation relies on sockindex
having been assigned a valid value, and that is only ever done either by EthernetClient::connect()
or by being explicitly set by EthernetServer::available()
.
-
in this example this is done to check if the client is availableLucas Noetzold– Lucas Noetzold2020年01月10日 20:34:22 +00:00Commented Jan 10, 2020 at 20:34
-
@LucasNoetzold That example makes no sense. Like many on the Arduino website it's complete nonsense. You should only check
if (client)
to confirm a connection has been established. Normally only when using it as an incoming connection to a server.Majenko– Majenko2020年01月10日 20:40:05 +00:00Commented Jan 10, 2020 at 20:40 -
As it states in the source code:
// the next function allows us to use the client returned by // EthernetServer::available() as the condition in an if-statement.
Majenko– Majenko2020年01月10日 20:42:09 +00:00Commented Jan 10, 2020 at 20:42 -
I'll have to find why connect is returning 0 then. Thanks.Lucas Noetzold– Lucas Noetzold2020年01月10日 20:54:11 +00:00Commented Jan 10, 2020 at 20:54
-
0 indicates DNS name resolve failure. github.com/arduino-libraries/Ethernet/blob/… @LucasNoetzoldMaximilian Gerhardt– Maximilian Gerhardt2020年01月10日 21:33:09 +00:00Commented Jan 10, 2020 at 21:33
!client
. This maps to the boolean operator which tells you if it has a connected socket (github.com/arduino-libraries/Ethernet/blob/…). Since you have not calledconnect()
on the client, this will always return false. What actual error do you have in your full sketch?