通過 Windows WinInet API 發起 HTTP 請求訪問 IP 查詢網站(如 ip138.com),從返回的 HTML 頁面中提取公網 IP 地址。
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#pragma comment(lib, "wininet.lib")
BOOL GetPubIp(char *ip) {
HINTERNET hInternet = NULL, hConnect = NULL;
char szText[512] = {0};
char *szAccept = "Accept: */*\r\n\r\n";
char *szUrl = "https://www.ip138.com/ip2city.asp";
DWORD dwReadLen = 0;
__try {
// 打開網絡會話
hInternet = InternetOpen("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (!hInternet) __leave;
// 打開 URL
hConnect = InternetOpenUrl(hInternet, szUrl, szAccept, strlen(szAccept),
INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0);
if (!hConnect) __leave;
// 讀取響應數據
InternetReadFile(hConnect, szText, sizeof(szText), &dwReadLen);
}
__finally {
if (hInternet) InternetCloseHandle(hInternet);
if (hConnect) InternetCloseHandle(hConnect);
}
// 解析 IP:頁面特徵 "您的IP地址是:[xxx.xxx.xxx.xxx]"
char *start = strstr(szText, "您的IP地址是:[");
if (!start) return FALSE;
start += 15; // 跳過特徵串長度
char *end = strstr(start, "]");
if (!end) return FALSE;
strncpy(ip, start, end - start);
ip[end - start] = '\0';
return TRUE;
}
int main() {
char myip[32] = {0};
if (GetPubIp(myip))
std::cout << "Public IP: " << myip << std::endl;
else
std::cout << "Failed to get public IP" << std::endl;
return 0;
}
INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD 確保獲取最新數據__try/__finally 保證句柄釋放https://ipinfo.io/ip 返回純文本 IP)INTERNET_FLAG_SECURE)curl ifconfig.meWinInet 提供了 Windows 平台輕量級 HTTP 客戶端能力,結合字符串解析可快速實現公網 IP 獲取。生產環境建議使用專用 IP 查詢 API 服務提高穩定性。