Ethernet Interface Using Mbed OS 5

Fork of TCPSocket_Example by mbed_example

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

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