Hi,
I need to check me external IP address so I found a code for a ESP_32 and it's working but... This code is (serial) printing more information than I need and since I want the IP to be sent to and OLED or LCD, I need to find a way to extract only the IP to send it in a variable and then print it on my OLED or LCD screen. I also need to compare it to the previous IP Check in order to get an alarm if the IP change.
This is what the code (serial) print right now:
{"ip":"70.85.117.188"}HTTP/1.1 200 OK
Server: nginx/1.25.2
Date: Tue, 03 Oct 2023 12:39:20 GMT
Content-Type: application/json
Content-Length: 22
Connection: keep-alive
Vary: Origin
This is the code I found
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#else
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "MyRooterName"
#define WIFI_PASSWORD "MySSID_Pass"
int connectedLED = 16;
void setup(){
Serial.begin(9600);
digitalWrite(connectedLED, LOW);
pinMode(connectedLED, OUTPUT);
#if defined(ARDUINO_ARCH_SAMD)
while (!Serial);
Serial.println();
Serial.println("");
#endif
wi_fi_startup();
}
void wi_fi_startup(){
Serial.print("Connecting to AP");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED){
Serial.println(".");
delay(200);}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Ready");
delay(2000);
}
void connectionCheck(){
if(WiFi.status()>= WL_CONNECTED){
digitalWrite(connectedLED, HIGH);
}else{
digitalWrite(connectedLED, LOW);
}
}
void GetExternalIP()
{
WiFiClient client;
if (!client.connect("api.ipify.org", 80)) {
Serial.println("Failed to connect with 'api.ipify.org' !");
}
else {
int timeout = millis() + 5000;
client.print("GET /?format=json HTTP/1.1\r\nHost: api.ipify.org\r\n\r\n");
while (client.available() == 0) {
if (timeout - millis() < 0) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
int size;
while ((size = client.available()) > 0) {
uint8_t* msg = (uint8_t*)malloc(size);
size = client.read(msg, size);
Serial.write(msg, size);
free(msg);
}
}
}
void loop(){
connectionCheck();
GetExternalIP();
delay(500);
}
If I type "api.ipify.org" in my browser I see my external IP so I know this is probably where I need to begin but getting help would be nice.
Thanks.