Get external IP address

Howdy all,is it possible to get external ip of my board by blynk widgets or something ?
Actually i am able to get my global ip with piece of code and print to blynk terminal.
But output of that code brings too much info.That’s why i am looking for any other simple solution.

My code:

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);
      terminal.flush();
      terminal.write(msg, size);
      terminal.flush();
      free(msg);
    }
  }
}

Your hardware has own IP. Your router have another IP. What IP do you need? And why would you need it?

Good question, i would like to update&upgrade my sketchs with OTA over internet. and looking to find a way.Do you think it’s possible @Dmitry ?

Ir depends on hardware. With some of it - it is impossible.

All ESP’s except the 01 (memory generally too small) can do OTA updates.
It isn’t normally based on an external IP though.
A server holds your firmware and your sketch looks for the new firmware and does the OTA update.

I figured out all steps with my NodeMCU,now i need to solve ip forwarding. :slight_smile:

Here is my code:

#define BLYNK_PRINT Serial
#include <BlynkSimpleEsp8266.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WebServer.h>
#include <SimpleTimer.h>
#include <ESP8266mDNS.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoOTA.h>
#include <WiFiUdp.h>
#include <SPI.h>

extern "C" {
#include "user_interface.h"
uint16 readvdd33(void);
}

ESP8266WebServer server(8266);
const char* serverIndex = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
const char* host = "NodeMCU-webupdate";
char auth[] = "xxx";
const int BlueLED =  D4;
int ledState = LOW;
long previousMillis = 0;
long interval = 1000;

WidgetTerminal terminal(V20);
ESP8266WiFiMulti wifiMulti;
boolean connectioWasAlive = true;
SimpleTimer upload;
WidgetLCD lcd(V19);
IPAddress myip;

int voltage = readvdd33();
int Led1=D8;
int Led2=D9;
long rssi;

void beep(unsigned char delayms)
{
  analogWrite(14, 20);
  delay(delayms);
  analogWrite(14, 0);
  delay(delayms);
}

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);
      terminal.flush();
      terminal.write(msg, size);
      terminal.flush();
      free(msg);
    }
  }
}

void DataUpload()
{
  Blynk.virtualWrite(V11, millis() / 3600000);                   // Uptime Hours
  Blynk.virtualWrite(V12, millis() / 60000);                   // Uptime Minutes
  Blynk.virtualWrite(V13,readvdd33());
  terminal.flush();
  terminal.println(F("--IoT Voltage Monitor--"));
  terminal.flush();
}

void WebUpdate() {
  Serial.println("WebUpdate is booting");
  terminal.flush();
  terminal.println("WebUpdate is booting");
  if(WiFi.waitForConnectResult() == WL_CONNECTED){
    MDNS.begin(host);
    server.on("/", HTTP_GET, [](){
      server.sendHeader("Connection", "close");
      server.send(200, "text/html", serverIndex);
    });
    server.on("/update", HTTP_POST, [](){
      server.sendHeader("Connection", "close");
      server.send(200, "text/plain", (Update.hasError())?"FAIL":"OK");
      ESP.restart();
    },[](){
      HTTPUpload& upload = server.upload();
      if(upload.status == UPLOAD_FILE_START){
        Serial.setDebugOutput(true);
        WiFiUDP::stopAll();
        Serial.printf("Update: %s\n", upload.filename.c_str());
        uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
        if(!Update.begin(maxSketchSpace)){
          Update.printError(Serial);
        }
      } else if(upload.status == UPLOAD_FILE_WRITE){
        if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
          Update.printError(Serial);
        }
      } else if(upload.status == UPLOAD_FILE_END){
        if(Update.end(true)){ //true to set the size to the current progress
          Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
          terminal.flush();
        } else {
          Update.printError(Serial);
        }
        Serial.setDebugOutput(false);
      }
      yield();
    });
    server.begin();
    MDNS.addService("http", "tcp", 80);
    Serial.printf("Ready! Open http://%s.local:8266 in your browser\n", host);
    terminal.println("Ready! Open http:NodeMCU-webupdate:8266 in your browser");
    terminal.flush();
  } else {
    Serial.println("WiFi Failed");
    terminal.println("WiFi Failed");
    terminal.flush();
  }
}

void setup()
{
  beep(300);
  beep(300);
  beep(50);
  beep(300);
  beep(300);
  Serial.begin(115200);
  wifiMulti.addAP("ssidxxx", "passxxx");                           //No 1 SSID
  wifiMulti.addAP("xxxSSID", "xxxpass");                          //No 2 SSID
  ArduinoOTA.setHostname("NodeMCU-IoT");
  Blynk.config(auth);
  Blynk.connect(3333);
  ArduinoOTA.setPassword((const char *)"OTAxxxPass");
  ArduinoOTA.begin();
  pinMode(BlueLED, OUTPUT);
  pinMode(V25, OUTPUT);
  pinMode(V26, OUTPUT);
  unsigned long maxMillis=millis() + 8000;
  while ((Blynk.connect() == false) && ( millis() <= maxMillis)) {
  }
  myip = WiFi.localIP();
  Blynk.notify("NodeMCU Started!");
  terminal.println("...Terminal opened...");
  terminal.flush();
  terminal.println(F("Blynk v" BLYNK_VERSION ));
  terminal.println(F("-------------"));
  terminal.println(F("---NodeMCU---"));
  terminal.println(F("IoT Voltage Monitor"));
  terminal.println(F("by elanozturk"));
  terminal.flush();
  upload.setInterval(30000L, DataUpload);
}

BLYNK_WRITE(V20)
{
  if (String("Auth") == param.asStr()) {
    terminal.flush();
    terminal.println(String(auth)) ;
    terminal.flush();
  }
  else if (String("Ssid") == param.asStr()) {
    terminal.flush();
    terminal.println(WiFi.SSID()) ;
    terminal.flush();
  }
  else if (String("Volt") == param.asStr()) {
    terminal.flush();
    terminal.println(String(voltage));
    terminal.flush();
  }
  else if (String("Rst") == param.asStr()) {
     terminal.flush();
     terminal.println(F("IoT Voltage Monitor going to restart..."));
     terminal.flush();
     ESP.reset();
  }
  else if (String("Ip") == param.asStr()) {
   terminal.flush();
   GetExternalIP();
 } else {
    terminal.flush();
    terminal.print("unknown command:");
    terminal.write(param.getBuffer(), param.getLength());
    terminal.println();
    terminal.flush();
  }
  terminal.flush();
}


BLYNK_WRITE(V8)                                                 // Wifi strength
{
 int pinData = param.asInt();
 if(pinData==1) {
   lcd.clear();
   lcd.print(0 ,0,"Wifi Strength");
   lcd.print(0 ,1,rssi);
 } else {
   lcd.print(0 ,0,"Voltage Monitor");
   lcd.print(0 ,1,"by elanozturk");
 }
}

BLYNK_WRITE(V9)                                                    // IP Address
{
 int pinData = param.asInt();
 if(pinData==1) {
   lcd.clear();
   lcd.print(0 ,0,"IP ADDRESS:");
   String fullip = String(myip[0]) + "." + myip[1] + "." + myip[2] + "." + myip[3];
   lcd.print(0, 1, fullip);
 } else {
   lcd.print(0 ,0,"Voltage Monitor");
   lcd.print(0 ,1,"by elanozturk");
 }
}

BLYNK_WRITE(V25)                                                       //OTA Web Update mode Start
{
  int pinData = param.asInt();

  if (pinData == 1)
  {
    WebUpdate();
  }
}

BLYNK_WRITE(V26)                                                       //Reset Button
{
  int pinData = param.asInt();

  if (pinData == 1)
  { Serial.println("IoT Voltage Monitor going to restart...");
    terminal.flush();
    terminal.println(F("IoT Voltage Monitor going to restart..."));
    terminal.flush();
    ESP.reset();
  }
}

void monitorWiFi()
{
  if (wifiMulti.run() != WL_CONNECTED)
  {
    if (connectioWasAlive == true)
    {
      connectioWasAlive = false;
      Serial.print("Looking for WiFi ");
    }
    Serial.print(".");
    delay(500);
  }
  else if (connectioWasAlive == false)
  {
    connectioWasAlive = true;
    Serial.printf(" connected to %s\n", WiFi.SSID().c_str());
  }
}

void loop()
{
  monitorWiFi();
  Blynk.run();
  server.handleClient();
  ArduinoOTA.handle();
  upload.run();
  rssi=WiFi.RSSI();
  myip=WiFi.localIP();
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval)
  {
    previousMillis = currentMillis;
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    digitalWrite(BlueLED, ledState);
  }
}

1 Like