Skip to content

Instantly share code, notes, and snippets.

@manchoz
Created January 29, 2021 11:29
Show Gist options
  • Save manchoz/347073663a063db0ce03306a527b78aa to your computer and use it in GitHub Desktop.
Save manchoz/347073663a063db0ce03306a527b78aa to your computer and use it in GitHub Desktop.
Example of Arduino Portenta H7 w/ Vision Shield Ethernet (mbedOS API) with Hostname as Char Array
#include "EthernetInterface.h"
EthernetInterface net;
void setup()
{
Serial.begin(115200);
while (!Serial)
;
Serial.println("Ethernet example for H7 + Vision Shield/PMC");
// Bring up the ethernet interface
net.connect();
// Show the network address
SocketAddress addr;
net.get_ip_address(&addr);
Serial.print("IP address: ");
Serial.println(addr.get_ip_address() ? addr.get_ip_address() : "None");
// Open a socket on the network interface, and create a TCP connection to mbed.org
TCPSocket socket;
socket.open(&net);
char hostname[] { "ifconfig.io" };
net.gethostbyname(hostname, &addr);
addr.set_port(80);
socket.connect(addr);
char request[256];
memset(request, 0, sizeof(request));
// Or (if you feel more C++) just:
// char request[256] { };
sprintf(request, "GET / HTTP/1.1\r\nHost: %s\r\nUser-Agent: curl/7.64.1\r\nAccept: */*\r\nConnection: close\r\n\r\n", hostname);
auto scount = socket.send(request, strlen(request));
Serial.print("Sent ");
Serial.print(scount);
Serial.println(" bytes: ");
Serial.print(request);
// Receive a simple HTTP response
const size_t rlen { 64 };
char rbuffer[rlen + 1] {};
size_t rcount;
size_t rec { 0 };
String response;
while ((rec = socket.recv(rbuffer, rlen)) > 0) {
rcount += rec;
response += rbuffer;
memset(rbuffer, 0, rlen);
}
Serial.print("Received ");
Serial.print(rcount);
Serial.println(" bytes: ");
Serial.println(response);
const String clTag = "Content-Length: ";
auto clIndex = response.indexOf(clTag);
clIndex += clTag.length();
auto cl = response.substring(clIndex, clIndex + 2);
const String bodyTag = "\r\n\r\n";
auto bodyIndex = response.indexOf(bodyTag);
if (bodyIndex != -1) {
bodyIndex += bodyTag.length();
auto body = response.substring(bodyIndex, bodyIndex + cl.toInt());
Serial.print("My public IPv4 Address is: ");
Serial.println(body);
}
// Close the socket to return its memory and bring down the network interface
socket.close();
// Bring down the ethernet interface
net.disconnect();
Serial.println("Done");
}
void loop()
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment