As I posted before I'm totally new to C.

In bash i can use

IP = "`wget -O - -q icanhazip.com`"
echo $IP

=

and it returns my ip.

However I'm trying hard to get this via curl although I don't quite understand how it works yet. I determined it is creating the ip.txt file but doesn't appear to be writing to it.

I also tried setting the CURLOPT_WRITEFUNCTION to NULL as suggested in the curl manual, this was supposed to send to stdout but nothing happened.


I checked the file read and that is OK if I manually enter some data.

Can someone help.

#include <string.h>

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <curl/curl.h>


char ipresult[128];


FILE *fp;

////////////////////////////////////////////////////

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
  int written = fwrite(ptr, size, nmemb, (FILE *)stream);
  return written;
}
 

int main(int argc, char **argv){   

{

CURL *curl;
	 
curl = curl_easy_init();

if(curl) {
fp =(FILE *) fopen("/tmp/ip.txt","w");
curl_easy_setopt(curl, CURLOPT_URL, "icanhazip.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

curl_easy_cleanup(curl);

fclose(fp);
}

{

fp =(FILE *) fopen("/tmp/ip.txt","r");

 fgets(ipresult,sizeof ipresult,fp);

 fclose(fp);

 printf("%s",ipresult);

}

return (0);


}
}

Ok, I gave up and used a bash call, I sent the info to a text file and parsed from there.

>> I gave up and used a bash call ..

Maybe give it another try .. adding a curl_easy_perform(curl) call there might work wonders ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.