C/C++, Hacking, Post-Exploitation, RedTeaming

HTTP – Get the external IP address in C

The following code snippets is from Post-recon project. This project is a work in progress.

Please visit GitHub for the full source code, in this post I will just point out the most interesting parts.

Get Public IP address (HTTP)

 
{...}
 
#define PUBLIC_IP_URL      "http://ipecho.net/plain"
 
{...}
 
int LibCurl::GetPublicIPv4Address(char **ip, const char *userAgent, long verbose)
{
    CURL *curl;
    data_size download_ctx;
    int size = 0;
 
    download_ctx.data = (char*)Common::hAlloc(1);
    download_ctx.size = 0;
 
    if ((curl = curl_easy_init()))
    {
        curl_easy_setopt(curl, CURLOPT_URL, PUBLIC_IP_URL);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, verbose); //debug, turn it off on production
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _write_function_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &download_ctx);
        curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent);
 
        if (curl_easy_perform(curl) == CURLE_OK) {
 
            if ((*ip = (char*)Common::hAlloc((download_ctx.size + 1) * sizeof(char))) != NULL) {
 
                if (Common::CopyString(*ip, download_ctx.size + 1, download_ctx.data) != 0) {
                    Common::hFree(*ip);
                    *ip = NULL;
                    size = -1;
                }
 
                size = download_ctx.size;
            }
        }
 
        curl_easy_cleanup(curl);
        Common::hFree(download_ctx.data);
        download_ctx.data = NULL;
    }
    else {
        size = -1;
    }
 
    return size;
}