-->
Page 1 of 2

[SOLVED] Getting Public IP through ESP8266

PostPosted: Sat Dec 03, 2016 8:33 am
by Ayush Sharma
Hello,
I want to Know , if i can Get Public IP of my Router through ESP8266 ?
ESP8266 Connects --> Router --> ESP Gets to Know Public IP and Stores it.

Is there any Arduino Code Lines for this ?

Re: Getting Public IP through ESP8266

PostPosted: Sat Dec 03, 2016 9:08 am
by martinayotte
The following code will print your external IP on Serial :

Code: Select allvoid 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);
    }
  }
}

Re: Getting Public IP through ESP8266

PostPosted: Sat Dec 03, 2016 9:43 am
by Ayush Sharma
Works... Thank You!

Re: [SOLVED] Getting Public IP through ESP8266

PostPosted: Mon Dec 19, 2016 4:48 pm
by elanozturk
Thank you @martinayotte ,your code helped me a lot. But is there any chance to get just ip address instead of whole message,i used the code with blynk to redirect serial print to terminal screen.

Code: Select allvoid 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);
  }
  }
}