TCP Socket Hello World with Ethernet

Dependencies:   mbed mbed-rtos EthernetInterface

Dependents:   PLC_client lanGpio_2v0

mbed 2 and mbed OS 5

This is an mbed 2 example. For an mbed-os example, please see:

Import programmbed-os-example-sockets

This is a quick example of a simple HTTP client program using the network-socket API that is provided as a part of mbed-os. The program brings up an underlying network interface, and uses it to perform an HTTP transaction over a TCPSocket.

main.cpp

Committer:
Kojto
Date:
2014-05-14
Revision:
14:72be2b8b7f24
Parent:
11:59dcefdda506

File content as of revision 14:72be2b8b7f24:

#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) {}
}