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.

Committer:
mbed_official
Date:
Wed Mar 08 20:30:07 2017 +0000
Revision:
12:2e7466eba9a3
Parent:
5:3e952c60d705
Child:
13:ed9e4aa00044
Merge pull request #8 from ARMmbed/iriark01-patch-1

Changing link to latest
.
Commit copied from https://github.com/ARMmbed/mbed-os-example-sockets

Who changed what in which revision?

UserRevisionLine numberNew contents of line
mbed_official 0:17bd84fc5087 1 #include "mbed.h"
mbed_official 5:3e952c60d705 2 #include "EthernetInterface.h"
mbed_official 0:17bd84fc5087 3
mbed_official 5:3e952c60d705 4 // Network interface
mbed_official 5:3e952c60d705 5 EthernetInterface net;
mbed_official 0:17bd84fc5087 6
mbed_official 0:17bd84fc5087 7 // Socket demo
mbed_official 5:3e952c60d705 8 int main() {
mbed_official 5:3e952c60d705 9 // Bring up the ethernet interface
mbed_official 5:3e952c60d705 10 printf("Ethernet socket example\n");
mbed_official 5:3e952c60d705 11 net.connect();
mbed_official 0:17bd84fc5087 12
mbed_official 0:17bd84fc5087 13 // Show the network address
mbed_official 5:3e952c60d705 14 const char *ip = net.get_ip_address();
mbed_official 0:17bd84fc5087 15 printf("IP address is: %s\n", ip ? ip : "No IP");
mbed_official 0:17bd84fc5087 16
mbed_official 0:17bd84fc5087 17 // Open a socket on the network interface, and create a TCP connection to mbed.org
mbed_official 5:3e952c60d705 18 TCPSocket socket;
mbed_official 5:3e952c60d705 19 socket.open(&net);
mbed_official 0:17bd84fc5087 20 socket.connect("developer.mbed.org", 80);
mbed_official 0:17bd84fc5087 21
mbed_official 12:2e7466eba9a3 22 // Send an HTTP request
mbed_official 0:17bd84fc5087 23 char sbuffer[] = "GET / HTTP/1.1\r\nHost: developer.mbed.org\r\n\r\n";
mbed_official 0:17bd84fc5087 24 int scount = socket.send(sbuffer, sizeof sbuffer);
mbed_official 5:3e952c60d705 25 printf("sent %d [%.*s]\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
mbed_official 0:17bd84fc5087 26
mbed_official 12:2e7466eba9a3 27 // Receive an http response and print out the response line
mbed_official 0:17bd84fc5087 28 char rbuffer[64];
mbed_official 0:17bd84fc5087 29 int rcount = socket.recv(rbuffer, sizeof rbuffer);
mbed_official 5:3e952c60d705 30 printf("recv %d [%.*s]\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
mbed_official 0:17bd84fc5087 31
mbed_official 0:17bd84fc5087 32 // Close the socket to return its memory and bring down the network interface
mbed_official 0:17bd84fc5087 33 socket.close();
mbed_official 0:17bd84fc5087 34
mbed_official 5:3e952c60d705 35 // Bring down the ethernet interface
mbed_official 5:3e952c60d705 36 net.disconnect();
mbed_official 0:17bd84fc5087 37 printf("Done\n");
mbed_official 0:17bd84fc5087 38 }