cURL really is an awesome library and in cpp::daily we’re basically going to talk about using it with C++ ! We made a video with lots of details on how to use cURL via the command line and you can see this link: 12 TIPS for you to use the curl COMMAND as a NINJA .
But using it with C++ is a little more arduous task, but possible because many applications are made using cURL .
First of all make sure you have the cURL library installed on your system, examples:
Remember that it’s not the command, it’s the library
sudo emerge net-misc/curl # Gentoo, Funtoo, ...
sudo apt install libcurl3 # or libcurl4, for Debian, Ubuntu, Linux Mint, ...
There are many particularities in both writing code and compiling. But to keep it simple (because in the future we will have a more detailed video about cURL with C++), I’ll show you a code example that accesses the address: https://gnu.terminalroot.com.br/ip.php that returns access data like: Operating Systems, Browser, Architecture and IP number and we will get it with C++ .
Note that we need to include the header: #include <curl/curl.h>
and instantiate the CURL class, we also use the size_t WriteCallback
function to show us the return. Read and analyze the entire code for greater understanding.
Example: vim curl.cpp
#include <iostream>
#include <curl/curl.h>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp){
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main(){
CURL * curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://gnu.terminalroot.com.br/ip.php");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << readBuffer << std::endl;
}
return 0;
}
And to compile we need to inform the library to the compiler, for example:
c++ curl.cpp -lcurl -o get-data
If we run ./get-data
we will notice that the output will be with the data informed above, but we can filter and then get our IP address: global
./get-data | grep -i ip
IP: 201.51.63.71
Just with this basic example you can “have fun” with several possibilities!