Support get global IP address

This commit is contained in:
2026-05-09 21:55:01 +10:00
parent cffdeb223b
commit eb1244c936
4 changed files with 414 additions and 0 deletions
+234
View File
@@ -7,6 +7,10 @@
#include <comdef.h>
#include <Wbemidl.h>
#include <dxgi.h>
#include <WinSock2.h> // inet_pton, in_addr — must precede windns.h
#include <WS2tcpip.h>
#include <windns.h>
#include <winhttp.h>
#include "Utility.h"
#include <hwinfo/PCIMapper.h>
@@ -1089,6 +1093,82 @@ private:
std::vector<GpuAdapter> _gpuAdaptersTemplate; // immutable after Init()
};
// ============================================================================
// Tiny synchronous HTTPS GET helper, used by GetPublicNetworkInformation().
// 5 s timeout on every WinHTTP step. Returns full response body in `body`,
// human-readable failure reason in `err`. No retries — caller decides.
// ============================================================================
struct WinHttpHandle {
HINTERNET h{nullptr};
explicit WinHttpHandle(HINTERNET hh) : h(hh) {}
~WinHttpHandle() { if (h) WinHttpCloseHandle(h); }
WinHttpHandle(const WinHttpHandle&) = delete;
WinHttpHandle& operator=(const WinHttpHandle&) = delete;
explicit operator bool() const { return h != nullptr; }
};
bool HttpsGetBody(const wchar_t* host, const wchar_t* path,
std::string& body, std::string& err) {
WinHttpHandle session(WinHttpOpen(L"ANSCENTER-LicensingSystem/1.0",
WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0));
if (!session) { err = "WinHttpOpen failed"; return false; }
// Resolve / connect / send / receive — each capped at 5 s.
WinHttpSetTimeouts(session.h, 5000, 5000, 5000, 5000);
WinHttpHandle conn(WinHttpConnect(session.h, host,
INTERNET_DEFAULT_HTTPS_PORT, 0));
if (!conn) { err = "WinHttpConnect failed"; return false; }
WinHttpHandle req(WinHttpOpenRequest(conn.h, L"GET", path,
nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE));
if (!req) { err = "WinHttpOpenRequest failed"; return false; }
if (!WinHttpSendRequest(req.h,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
err = "WinHttpSendRequest failed: " + std::to_string(GetLastError());
return false;
}
if (!WinHttpReceiveResponse(req.h, nullptr)) {
err = "WinHttpReceiveResponse failed: " + std::to_string(GetLastError());
return false;
}
DWORD status = 0, statusSize = sizeof(status);
if (!WinHttpQueryHeaders(req.h,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &statusSize,
WINHTTP_NO_HEADER_INDEX)) {
err = "WinHttpQueryHeaders failed";
return false;
}
if (status != 200) {
err = "HTTP " + std::to_string(status);
return false;
}
DWORD avail = 0;
for (;;) {
if (!WinHttpQueryDataAvailable(req.h, &avail)) {
err = "WinHttpQueryDataAvailable failed";
return false;
}
if (avail == 0) break;
std::vector<char> buf(avail);
DWORD read = 0;
if (!WinHttpReadData(req.h, buf.data(), avail, &read)) {
err = "WinHttpReadData failed";
return false;
}
body.append(buf.data(), read);
}
if (body.empty()) { err = "empty response body"; return false; }
return true;
}
} // namespace
namespace ANSCENTER
@@ -1108,6 +1188,160 @@ namespace ANSCENTER
return info;
}
// ----------------------------------------------------------------------
// Public IPv4 via OpenDNS.
//
// `myip.opendns.com` is a special DNS name served by OpenDNS resolvers
// (208.67.222.222 / 208.67.220.220). The resolver returns an A record
// whose value IS the requesting client's public IP. One UDP/53 round
// trip — no HTTP, no third-party REST API, no database.
//
// Cached for 10 minutes; public IPs change rarely (typically only on
// ISP lease renewal or VPN toggle).
// ----------------------------------------------------------------------
std::string ANSLicenseHelper::GetPublicIPAddress()
{
static std::mutex mtx;
static std::string cachedIP;
static std::chrono::steady_clock::time_point lastFetch{};
std::lock_guard<std::mutex> lock(mtx);
const auto now = std::chrono::steady_clock::now();
if (!cachedIP.empty() &&
std::chrono::duration_cast<std::chrono::minutes>(now - lastFetch).count() < 10) {
return cachedIP;
}
// Pin the query to OpenDNS resolver1 — using the system's default
// resolver wouldn't work because most ISP resolvers don't honour
// the magic 'myip.opendns.com' name.
IP4_ARRAY dnsServers{};
dnsServers.AddrCount = 1;
DWORD opendns = 0;
if (inet_pton(AF_INET, "208.67.222.222", &opendns) != 1) {
ANS_DBG("PublicIP", "inet_pton failed for OpenDNS literal");
return cachedIP; // return whatever we had before, even if empty
}
dnsServers.AddrArray[0] = opendns;
PDNS_RECORDA records = nullptr;
const DNS_STATUS status = DnsQuery_A(
"myip.opendns.com",
DNS_TYPE_A,
DNS_QUERY_BYPASS_CACHE | DNS_QUERY_NO_HOSTS_FILE,
&dnsServers,
reinterpret_cast<PDNS_RECORD*>(&records),
nullptr);
std::string result;
if (status == ERROR_SUCCESS && records) {
for (PDNS_RECORDA r = records; r; r = r->pNext) {
if (r->wType == DNS_TYPE_A) {
in_addr a{};
a.S_un.S_addr = r->Data.A.IpAddress;
char buf[INET_ADDRSTRLEN] = {};
if (inet_ntop(AF_INET, &a, buf, sizeof(buf)) != nullptr)
result = buf;
break;
}
}
} else {
ANS_DBG("PublicIP", "DnsQuery_A status=0x%08lx", static_cast<unsigned long>(status));
}
if (records) DnsRecordListFree(records, DnsFreeRecordList);
if (!result.empty()) {
cachedIP = result;
lastFetch = now;
}
return result;
}
// ----------------------------------------------------------------------
// Public IP + IP-based geolocation via ipapi.co/json/.
//
// Single HTTPS GET; result cached 60 minutes on success, with a 60-second
// back-off on failure so a flapping network doesn't get hammered (every
// other call would otherwise wait for the 5 s WinHTTP timeout to expire).
//
// JSON keys we read (ipapi.co's documented schema):
// ip, country_name, country_code, region, city, org, timezone,
// latitude, longitude.
// ipapi.co reports rate-limit / blocked-IP errors as { "error": true,
// "reason": "..." } — those propagate into PublicNetworkInfo.error.
// ----------------------------------------------------------------------
PublicNetworkInfo ANSLicenseHelper::GetPublicNetworkInformation()
{
static std::mutex mtx;
static PublicNetworkInfo cache;
static std::chrono::steady_clock::time_point lastSuccess{};
static std::chrono::steady_clock::time_point lastAttempt{};
std::lock_guard<std::mutex> lock(mtx);
const auto now = std::chrono::steady_clock::now();
if (cache.ok &&
std::chrono::duration_cast<std::chrono::minutes>(now - lastSuccess).count() < 60) {
return cache;
}
// Failure backoff — don't retry within 60 s of a recent failed attempt.
if (!cache.ok &&
lastAttempt.time_since_epoch().count() != 0 &&
std::chrono::duration_cast<std::chrono::seconds>(now - lastAttempt).count() < 60) {
return cache;
}
lastAttempt = now;
PublicNetworkInfo info;
std::string body, err;
if (!HttpsGetBody(L"ipapi.co", L"/json/", body, err)) {
info.error = err;
ANS_DBG("PublicNet", "ipapi.co fetch failed: %s", err.c_str());
cache = info;
return info;
}
try {
boost::property_tree::ptree pt;
std::stringstream ss(body);
boost::property_tree::read_json(ss, pt);
if (pt.get<bool>("error", false)) {
info.error = pt.get<std::string>("reason", "ipapi.co reported an error");
ANS_DBG("PublicNet", "ipapi.co reported error: %s", info.error.c_str());
cache = info;
return info;
}
info.publicIP = pt.get<std::string>("ip", "");
info.country = pt.get<std::string>("country_name", "");
info.countryCode = pt.get<std::string>("country_code", "");
info.region = pt.get<std::string>("region", "");
info.city = pt.get<std::string>("city", "");
info.isp = pt.get<std::string>("org", "");
info.timezone = pt.get<std::string>("timezone", "");
info.latitude = pt.get<double> ("latitude", 0.0);
info.longitude = pt.get<double> ("longitude", 0.0);
info.ok = !info.publicIP.empty();
if (info.ok) {
cache = info;
lastSuccess = now;
ANS_DBG("PublicNet", "ipapi.co ok: ip=%s country=%s city=%s",
info.publicIP.c_str(), info.countryCode.c_str(), info.city.c_str());
} else {
info.error = "ipapi.co returned no IP field";
cache = info;
}
} catch (const std::exception& e) {
info.error = std::string("JSON parse: ") + e.what();
ANS_DBG("PublicNet", "JSON parse failed: %s", e.what());
cache = info;
}
return info;
}
EngineType ANSCENTER::ANSLicenseHelper::CheckHardwareInformation()
{
ANS_DBG("HWInfo", "CheckHardwareInformation: starting hardware detection");
+83
View File
@@ -392,6 +392,35 @@ namespace ANSCENTER
double netSendSpeedMBs = -1.0;
};
// ------------------------------------------------------------------------
// Public IP + IP-based geolocation, sourced from ipapi.co/json/.
//
// One HTTPS GET per refresh; results cached for 60 minutes (success) or
// 60 seconds (failure backoff). Never throws, never blocks more than 5 s.
//
// `ok == false` means the data could not be obtained — `error` carries
// the reason ("HTTP 429", "WinHttpConnect failed", "JSON parse: ...",
// etc.). Latitude/longitude are 0,0 when unknown.
//
// Privacy note: this performs an outbound HTTPS request to a third-party
// service (ipapi.co). Each request reveals the device's public IP to that
// service. Use the simpler GetPublicIPAddress() if you only need the IP
// and prefer no third-party HTTP hop.
// ------------------------------------------------------------------------
struct PublicNetworkInfo {
bool ok = false;
std::string publicIP; // e.g. "203.0.113.42"
std::string country; // full name, e.g. "Vietnam"
std::string countryCode; // ISO 2-letter, e.g. "VN"
std::string region; // state / province
std::string city;
std::string isp; // organization / provider name
std::string timezone; // IANA tz, e.g. "Asia/Ho_Chi_Minh"
double latitude = 0.0;
double longitude = 0.0;
std::string error; // empty on success
};
class ANSLICENSE_API SPDLogger
@@ -494,6 +523,24 @@ namespace ANSCENTER
[[nodiscard]] static bool LicenseVerification(std::string licenseKey, int productId, std::string registrationName);
[[nodiscard]] static EngineType CheckHardwareInformation();
[[nodiscard]] static SystemHealthInfo GetSystemHealthInformation();
// Returns the device's public IPv4 address as seen from the internet,
// or an empty string if it can't be resolved (no connectivity, DNS
// blocked, etc). Result is cached for 10 minutes — subsequent calls
// are a memory read.
//
// Implementation uses a single DNS query to OpenDNS's special name
// 'myip.opendns.com' (the resolver echoes back the client's seen IP
// in an A record). No HTTP, no third-party REST, no database — works
// on any network where outbound DNS to 208.67.222.222 is allowed
// (which is the vast majority, including most corporate firewalls).
[[nodiscard]] static std::string GetPublicIPAddress();
// Public IP + geolocation in one shot via ipapi.co/json/. See the
// PublicNetworkInfo doc-comment for caching, failure semantics, and
// privacy implications. If you only need the IP, prefer the simpler
// GetPublicIPAddress() above (no HTTP, no third-party REST).
[[nodiscard]] static PublicNetworkInfo GetPublicNetworkInformation();
[[nodiscard]] static std::string ListLicenses();
[[nodiscard]] static int ActivateTrialLicense(std::string productName);
[[nodiscard]] static int DeactivateLicense(std::string productName);
@@ -595,6 +642,42 @@ extern "C" __declspec(dllexport) int GetSystemHealthParameters(
// outer separator is never ambiguous.
// Returns 1 on success, 0 on failure.
extern "C" __declspec(dllexport) int GetSystemHealthParametersString(LStrHandle outString);
// Writes the device's public IPv4 (e.g. "203.0.113.42") into the LStrHandle.
// Returns 1 on success, 0 if the IP could not be resolved. Cached for 10 min.
extern "C" __declspec(dllexport) int GetPublicIPAddress(LStrHandle ipv4);
// Public IP + IP-based geolocation via ipapi.co/json/. Each pointer is
// optional; pass nullptr to skip a field. `errorMsg` carries a human-readable
// reason when the call fails (no internet, rate limit, etc.). Returns 1 on
// success, 0 on failure. Cached for 1 hour on success; 1-minute back-off on
// failure so a flapping network doesn't get hammered.
extern "C" __declspec(dllexport) int GetPublicNetworkParameters(
LStrHandle publicIP,
LStrHandle country,
LStrHandle countryCode,
LStrHandle region,
LStrHandle city,
LStrHandle isp,
LStrHandle timeZone,
double* latitude,
double* longitude,
LStrHandle errorMsg);
// Same payload packed as a single ';'-separated string in this exact order:
// 1 publicIP
// 2 country (full name)
// 3 countryCode (ISO 2-letter)
// 4 region
// 5 city
// 6 isp
// 7 timezone (IANA, e.g. "Asia/Ho_Chi_Minh")
// 8 latitude (6dp, C locale)
// 9 longitude (6dp, C locale)
// Any literal ';' inside string fields is rewritten to ',' so the separator
// stays unambiguous. Returns 1 on success, 0 on failure (string still written
// — values just empty/0).
extern "C" __declspec(dllexport) int GetPublicNetworkParametersString(LStrHandle outString);
extern "C" __declspec(dllexport) int ReleaseLoggers();
extern "C" __declspec(dllexport) int ListANSLicenses(std::string &listLicense);
extern "C" __declspec(dllexport) int ListANSLicenses_LV(LStrHandle ansProductLicenses);
+1
View File
@@ -55,6 +55,7 @@ target_link_libraries(ANSLicensingSystem PRIVATE
pdh.lib psapi.lib
wbemuuid.lib oleaut32.lib ole32.lib
dxgi.lib
dnsapi.lib
${WIN_COMMON_LIBS}
)
+96
View File
@@ -449,6 +449,102 @@ extern "C" __declspec(dllexport) int GetSystemHealthParameters(
}
}
extern "C" __declspec(dllexport) int GetPublicIPAddress(LStrHandle ipv4) {
try {
if (!ipv4) return 0;
const std::string s = ANSCENTER::ANSLicenseHelper::GetPublicIPAddress();
const int size = static_cast<int>(s.length());
const MgErr err = DSSetHandleSize(ipv4, sizeof(int32) + size * sizeof(uChar));
if (err != noErr) return 0;
(*ipv4)->cnt = size;
if (size > 0) memcpy((*ipv4)->str, s.c_str(), size);
return s.empty() ? 0 : 1;
} catch (...) {
return 0;
}
}
namespace {
inline void WriteLStr(LStrHandle h, const std::string& s) {
if (!h) return;
const int size = static_cast<int>(s.length());
const MgErr err = DSSetHandleSize(h, sizeof(int32) + size * sizeof(uChar));
if (err == noErr) {
(*h)->cnt = size;
if (size > 0) memcpy((*h)->str, s.c_str(), size);
}
}
}
extern "C" __declspec(dllexport) int GetPublicNetworkParameters(
LStrHandle publicIP,
LStrHandle country,
LStrHandle countryCode,
LStrHandle region,
LStrHandle city,
LStrHandle isp,
LStrHandle timeZone,
double* latitude,
double* longitude,
LStrHandle errorMsg)
{
try {
const ANSCENTER::PublicNetworkInfo info =
ANSCENTER::ANSLicenseHelper::GetPublicNetworkInformation();
WriteLStr(publicIP, info.publicIP);
WriteLStr(country, info.country);
WriteLStr(countryCode, info.countryCode);
WriteLStr(region, info.region);
WriteLStr(city, info.city);
WriteLStr(isp, info.isp);
WriteLStr(timeZone, info.timezone);
WriteLStr(errorMsg, info.error);
if (latitude) *latitude = info.latitude;
if (longitude) *longitude = info.longitude;
return info.ok ? 1 : 0;
} catch (...) {
return 0;
}
}
extern "C" __declspec(dllexport) int GetPublicNetworkParametersString(LStrHandle outString) {
try {
if (!outString) return 0;
const ANSCENTER::PublicNetworkInfo info =
ANSCENTER::ANSLicenseHelper::GetPublicNetworkInformation();
auto sanitize = [](std::string s) {
std::replace(s.begin(), s.end(), ';', ',');
return s;
};
std::ostringstream os;
os.imbue(std::locale::classic());
os << std::fixed << std::setprecision(6);
os << sanitize(info.publicIP) << ';'
<< sanitize(info.country) << ';'
<< sanitize(info.countryCode) << ';'
<< sanitize(info.region) << ';'
<< sanitize(info.city) << ';'
<< sanitize(info.isp) << ';'
<< sanitize(info.timezone) << ';'
<< info.latitude << ';'
<< info.longitude;
const std::string s = os.str();
const int size = static_cast<int>(s.length());
const MgErr err = DSSetHandleSize(outString, sizeof(int32) + size * sizeof(uChar));
if (err != noErr) return 0;
(*outString)->cnt = size;
if (size > 0) memcpy((*outString)->str, s.c_str(), size);
return info.ok ? 1 : 0;
} catch (...) {
return 0;
}
}
extern "C" __declspec(dllexport) int GetSystemHealthParametersString(LStrHandle outString) {
try {
if (!outString) return 0;