Nenad Jovicic / Mbed OS mbed-os-PMK2018_tcp_client
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "TCPSocket.h"
00003 #include "EthernetInterface.h"
00004 
00005 EthernetInterface eth;
00006 TCPSocket socket;
00007 
00008 int main()
00009 {
00010     printf("Basic TCP client example\n");
00011 
00012     // Brings up the network interface
00013     eth.connect();
00014     const char *ip = eth.get_ip_address();
00015     const char *mac = eth.get_mac_address();
00016     printf("IP address is: %s\n", ip ? ip : "No IP");
00017     printf("MAC address is: %s\n", mac ? mac : "No MAC");
00018 
00019     // Open a socket on the network interface, and create a TCP connection to mbed.org
00020     socket.open(&eth);
00021     socket.connect("192.168.0.108", 80);
00022 
00023     // Send data
00024     char sbuffer[] = "12345";
00025     int scount = socket.send(sbuffer, sizeof sbuffer);
00026     printf("sent %d [%.*s]\r\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
00027 
00028     // Recieve a simple http response and print out the response line
00029     char rbuffer[64];
00030     int rcount = socket.recv(rbuffer, sizeof rbuffer);
00031     printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
00032 
00033     // Close the socket to return its memory and bring down the network interface
00034     socket.close();
00035     eth.disconnect();
00036 
00037     printf("Done\n");
00038 }