| /* You need to compile this with libcurl in order to work */ |
| #include <stdio.h> |
| #include <stdlib.h> |
| #include <string.h> |
| |
| #include <curl/curl.h> |
| #include <curl/types.h> |
| #include <curl/easy.h> |
| struct MemoryStruct { |
| char *memory; |
| size_t size; |
| }; |
| |
| static void *myrealloc(void *ptr, size_t size) |
| { |
| if(ptr) |
| return realloc(ptr, size); |
| else |
| return malloc(size); |
| } |
| |
| static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) |
| { |
| size_t realsize = size * nmemb; |
| struct MemoryStruct *mem = (struct MemoryStruct *)data; |
| |
| mem->memory = (char *)myrealloc(mem->memory, mem->size + realsize + 1); |
| if (mem->memory) { |
| memcpy(&(mem->memory[mem->size]), ptr, realsize); |
| mem->size += realsize; |
| mem->memory[mem->size] = 0; |
| } |
| return realsize; |
| } |
| |
| int main(int argc, char **argv) |
| { |
| CURL *curl_handle; |
| |
| struct MemoryStruct chunk; |
| |
| chunk.memory=NULL; |
| chunk.size = 0; |
| |
| curl_global_init(CURL_GLOBAL_ALL); |
| |
| curl_handle = curl_easy_init(); |
| curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.timezoneauthority.com/ws/tz.html?who=demo&ip=18.18.18.18"); |
| curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); |
| curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); |
| curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); |
| curl_easy_perform(curl_handle); |
| curl_easy_cleanup(curl_handle); |
| |
| /* Do something with chunk.memory */ |
| |
| if(chunk.memory) |
| free(chunk.memory); |
| |
| return 0; |
| } |