流程:请求 API → 解析 JSON(简单解析或使用 nlohmann/json)→ 使用返回代理访问目标站。
#include <curl/curl.h>
#include <string>
#include <iostream>
#include <nlohmann/json.hpp>
static size_t Write(void* contents, size_t size, size_t nmemb, void* userp){
((std::string*)userp)->append((char*)contents, size*nmemb);
return size*nmemb;
}
int main(){
std::string api = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";
CURL* curl = curl_easy_init();
std::string buf;
if(!curl) return 1;
curl_easy_setopt(curl, CURLOPT_URL, api.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
CURLcode res = curl_easy_perform(curl);
if(res != CURLE_OK){ std::cerr << "API失败: " << curl_easy_strerror(res) << std::endl; return 1; }
curl_easy_cleanup(curl);
// 使用 nlohmann/json 解析返回的 JSON
std::string ip;
int port = 0;
try {
auto j = nlohmann::json::parse(buf);
if (j.is_array() && !j.empty()) {
ip = j.at(0).at("ip").get<std::string>();
port = j.at(0).at("port").get<int>();
} else if (j.is_object()) {
ip = j.at("ip").get<std::string>();
port = j.at("port").get<int>();
} else {
std::cerr << "解析失败: 返回 JSON 结构不符合预期" << std::endl;
return 1;
}
} catch (const std::exception& e) {
std::cerr << "解析失败: " << e.what() << std::endl;
return 1;
}
// 使用代理访问 httpbin
std::string page;
curl = curl_easy_init();
if(!curl) return 1;
curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/ip");
std::string proxy = std::string("http://") + ip + ":" + std::to_string(port);
curl_easy_setopt(curl, CURLOPT_PROXY, proxy.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &page);
res = curl_easy_perform(curl);
if(res != CURLE_OK){ std::cerr << "访问失败: " << curl_easy_strerror(res) << std::endl; return 1; }
curl_easy_cleanup(curl);
std::cout << page << std::endl;
return 0;
}