首先,确保安装了CURL库
C++
#include <iostream>
#include <curl/curl.h>
size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
std::string getExternalIP() {
CURL *curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://ifconfig.me/ip");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
return readBuffer;
}
int main() {
std::string ip = getExternalIP();
std::cout << "External IP: " << ip << std::endl;
return 0;
}
php
function get_out_ip(){
$curl = curl_init();
// 要访问的API URL
$apiUrl = 'http://ipinfo.io/ip';
curl_setopt_array($curl, array(
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
// 执行请求,获取响应
$response = curl_exec($curl);
$err = curl_error($curl);
// 关闭cURL资源,并释放系统资源
curl_close($curl);
if ($err) {
return "";
} else {
// 输出外网IP
saveLog("-------get_out_ip-----".$response);
return $response;
}
}