ed557

学习笔记

libcurl 发送HTTP请求时获取目标IP

#include "curl/curl.h"


int main() {
    char* ip;
    CURL* curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "https://baidu.com");
    CURLcode res = curl_easy_perform(curl);
    if(res == CURLE_OK && !curl_easy_getinfo(curl, CURLINFO_PRIMARY_IP, &ip) && ip) {
        printf("IP: %s\n", ip);
    }
    int response_code;
    if (!curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code)){
       printf("Status Code: %d\n", response_code);
    }
    curl_easy_cleanup(curl);
    return 0;
}

输出:

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>bfe/1.0.8.18</center>
</body>
</html>
IP: 39.156.66.10
Status Code: 302

可以通过 CURLINFO_PRIMARY_IP 获取curl最近一次的连接IP

https://curl.se/libcurl/c/CURLINFO_PRIMARY_IP.html

CURLINFO_PRIMARY_IP explained

Pass a pointer to a char pointer to receive the pointer to a null-terminated string holding the IP address of the most recent connection done with this curl handle. This string may be IPv6 when that is enabled. Note that you get a pointer to a memory area that will be re-used at next request so you need to copy the string if you want to keep the information.

The ip pointer will be NULL or pointing to private memory you MUST NOT free - it gets freed when you call curl_easy_cleanup on the corresponding CURL handle.

Availability

Added in 7.19.0

 

posted on 2022-11-15 22:55  ed557  阅读(163)  评论(0编辑  收藏  举报

导航