8 years, 5 months ago.

Ethernet can't work ?

Why I use this example I only see my IP Address is, I didn't see anything response.

#include "mbed.h"
#include "EthernetInterface.h"
 
int main() {
    EthernetInterface eth;
    eth.init(); //Use DHCP
    eth.connect();
    printf("IP Address is %s\n", eth.getIPAddress());
    
    TCPSocketConnection sock;
    sock.connect("mbed.org", 80);
    
    char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt HTTP/1.0\n\n";
    sock.send_all(http_cmd, sizeof(http_cmd)-1);
    
    char buffer[300];
    int ret;
    while (true) {
        ret = sock.receive(buffer, sizeof(buffer)-1);
        if (ret <= 0)
            break;
        buffer[ret] = '\0';
        printf("Received %d chars from server:\n%s\n", ret, buffer);
    }
      
    sock.close();
    
    eth.disconnect();
    
    while(1) {}
}

Question relating to:

mbed IP library over Ethernet ethernet, ip, mbed

1 Answer

8 years, 5 months ago.

Uhm...

Probably the problem is you don't give the server time to respond. Please insert some wait time before you enter the while loop for reading the response of the server.

wait(1.0);
int ret;
    while (true) {
        ret = sock.receive(buffer, sizeof(buffer)-1);
        if (ret <= 0)
            break;
        buffer[ret] = '\0';
        printf("Received %d chars from server:\n%s\n", ret, buffer);
    }

A better solution would be to wait until data is available and use a time-out of e.g. 5 seconds. If data becomes available, read the data until no data is available anymore. Would be something like this...

/* Wait until data becomes available or a time-out of 5000ms */
tstart = millis();
int ret;
do {
    ret = sock.receive(buffer, sizeof(buffer)-1);
} while ( (ret<=0) && ((tstart-millis())<5000) );

/* If data is available, read and print data to terminal */
while (ret>0) {
    printf("Received %d chars from server:\n%s\n", ret, buffer);
    ret = sock.receive(buffer, sizeof(buffer)-1);
}