Chat freely about anything...

User avatar
By pras
#65038 Hi,
I am struggling with this. I am trying to get only the IP (and not all the http data) and then send it via Telegram to the user.
I can get the ip only as a variable.
Can you please help?
Thank you!
User avatar
By Ramotny
#90380 This thread is a bit old but maybe my post will help someone.

The reply from api.ipify.org with @format=text contains public IP in last line of reply (after CR/LF)
So easiest way to get it is to search the reply back for LF (10d, 0Ah) and then You get "pure" IP:

String PublIP; // global string pointer to use anywhere in prog
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=text 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;
}
}
// end of ipify inquiry

int nbytes; // number of characters waiting from Ipify
int ii; // just counter for char read

while ((nbytes = client.available()) > 0) {
char* IpifyReply = (char*)malloc(nbytes +1); // allocate memory for reply string
for (ii = 0; ii < nbytes; ii++) // read char by char from reply
{ IpifyReply[ii] = client.read(); }
IpifyReply[ii] = 0; // add end of string

// ===== print web response for analysis where IP is
// Serial.println(nbytes);
// Serial.println(IpifyReply);
// ii = 0;
// while (IpifyReply[ii] >0)
// {
// Serial.print(IpifyReply[ii]);
// Serial.print(" ");
// Serial.println(int(IpifyReply[ii]));
// ii++;
// }
// Serial.println("00");
// ===== END-OF printout web response for data analysis

// last line after CR+LF contains IP: .......[CR][LF]xx.xxx.x.xxx[0]
// search input from end back for LF (chr(10) to find just IP without all junk text

// search backward for LineFeed (10d, 0Ah). --x = first decrement then output
while (IpifyReply[--nbytes] != 10) { }

// assign new (moved) pointer to new global ptr pointing last string from input.
// PublIP has been declared anywhere outside function/procedure to be global as
// String PublIP; // pointer to global externalIP string
PublIP = IpifyReply + nbytes + 1; // +1 beacuse when found points to LF an should for next char

Serial.println(PublIP);
}
}
}