Chat freely about anything...

User avatar
By Ayush Sharma
#59039 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 ?
Last edited by Ayush Sharma on Sat Dec 03, 2016 9:44 am, edited 1 time in total.
User avatar
By martinayotte
#59042 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);
    }
  }
}
User avatar
By elanozturk
#59712 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);
  }
  }
}