In this post, I want to show you how to use cURLpp (C++ wrapper around libcURL) to make a simple HTTP query to ip-api.com in order to retrieve geolocation information of a given host or IP address. I chose cURLpp because it’s simple and easy to use; the example program would not have been any harder using libcURL C API but this is a C++ blog after-all. I will be using Boost Property Tree library to deserialize the JSON geo-ip data. All of that is achieved in 15, give or take, lines of actual code… that’s the power of simple and well designed C++ libraries!
The program starts off by setting up a RAII object of type...
curlpp::Cleanup
...which initializes and cleans up cURLpp
library. We then create a request object of type...
curlpp::Easy
...and an output...
std::stringstream
...where the received data will be placed. Next we setup some options like verbosity level, URL, port, the output stream, and we execute the query. Finally, we parse the JSON data using...
read_json
...and iterate over the...
ptree
...structure to print it to the console.
geoip.cpp:
#include <iostream>
#include <sstream>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace std;
int main()
{
try
{
curlpp::Cleanup cURLppStartStop;
curlpp::Easy request;
std::stringstream response;
request.setOpt(curlpp::options::Verbose(true));
request.setOpt(curlpp::options::WriteStream(&response));
request.setOpt(curlpp::options::Url("http://ip-api.com/json/vorbrodt.blog"));
request.setOpt(curlpp::options::Port(80));
request.perform();
boost::property_tree::ptree data;
boost::property_tree::read_json(response, data);
for(auto& it : data)
cout << it.first << " = " << it.second.data() << endl;
}
catch(exception& e)
{
cerr << e.what() << endl;
}
}
Program output:
* Trying 69.195.146.130…
* TCP_NODELAY set
* Connected to ip-api.com (69.195.146.130) port 80 (#0)
> GET /json/vorbrodt.blog HTTP/1.1
Host: ip-api.com
Accept: */*
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Content-Type: application/json; charset=utf-8
< Date: Fri, 29 Mar 2019 23:17:53 GMT
< Content-Length: 284
<
* Connection #0 to host ip-api.com left intact
as = AS46606 Unified Layer
city = Provo
country = United States
countryCode = US
isp = Unified Layer
lat = 40.2067
lon = -111.643
org = Unified Layer
query = 162.241.253.105
region = UT
regionName = Utah
status = success
timezone = America/Denver
zip = 84606