A small example of TCP server over ethernet for mbed-os.

main.cpp

Committer:
nenad
Date:
2018-05-11
Revision:
3:48f60b2918aa
Parent:
1:ec61ea9f67de

File content as of revision 3:48f60b2918aa:

#include "mbed.h"
#include "TCPSocket.h"
#include "EthernetInterface.h"

EthernetInterface eth;
TCPSocket socket;

int main()
{
    printf("Basic TCP client example\n");

    // Brings up the network interface
    eth.connect();
    const char *ip = eth.get_ip_address();
    const char *mac = eth.get_mac_address();
    printf("IP address is: %s\n", ip ? ip : "No IP");
    printf("MAC address is: %s\n", mac ? mac : "No MAC");

    // Open a socket on the network interface, and create a TCP connection to mbed.org
    socket.open(&eth);
    socket.connect("192.168.0.108", 80);

    // Send data
    char sbuffer[] = "12345";
    int scount = socket.send(sbuffer, sizeof sbuffer);
    printf("sent %d [%.*s]\r\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);

    // Recieve a simple http response and print out the response line
    char rbuffer[64];
    int rcount = socket.recv(rbuffer, sizeof rbuffer);
    printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);

    // Close the socket to return its memory and bring down the network interface
    socket.close();
    eth.disconnect();

    printf("Done\n");
}