Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 994
  • Last Modified:

libcurl and ip address resolving

I'm using libcurl in my application to download some web sites. I need to know what IP address those web sites resolve to, to know the specific IP that my curl code is hitting. Is there any way to query the libcurl response to see what IP it actually hit, not just the domain?

The main reason for this is to know which load balanced server I'm hitting.

One option would be for me to get the IP address independently, but I wouldn't be guaranteed to get the same IP if the DNS rotates amongst a number. Or I could get the IP address first, then hit the IP address itself, but some domains require that you request the specific domain and not just the ip address.

Anyone have any other ideas?
  • 3
1 Solution
I guess using curl_easy_getinfo may help. http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html

#include <curl/curl.h>

CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ... );

Request internal information from the curl session with this function. The third argument MUST be a pointer to a long, a pointer to a char *, a pointer to a struct curl_slist * or a pointer to a double (as this documentation describes further down). The data pointed-to will be filled in accordingly and can be relied upon only if the function returns CURLE_OK. Use this function AFTER a performed transfer if you want to get transfer- oriented data.
You should not free the memory returned by this function unless it is explictly mentioned below.


Pass a pointer to a long to receive the last socket used by this curl session. If the socket is no longer valid, -1 is returned. When you finish working with the socket, you must call curl_easy_cleanup() as usual and let libcurl close the socket and cleanup other resources associated with the handle. This is typically used in combination with CURLOPT_CONNECT_ONLY. (Added in 7.15.2)

Here is my suggestion how to use it:

#include <sys/types.h>
#include <socket.h>
#include <curl/curl.h>
int sd;
struct  sockaddr_in  sd_name;
socklen_t sd_len;
curl_easy_getinfo(CURL *curl, CURLINFO_LASTSOCKET, sd);
getsockname(sd, &sd_name,  &sd_len);

// now your IP is sd_name.sin_addr.s_addr

how to call this code or where to insert - it's up to you, I didn't test it. Probably you need to register callback function right after connect and analise IP there.

fix: curl_easy_getinfo(CURL *curl, CURLINFO_LASTSOCKET, &sd); // with &sd
one more fix: getpeername() not getsockname() :-)

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now