Translated from Simplified Chinese by AI.Read the original
Over the past few days I threw together a small and beautiful little tool to deal with some tricky CDN geo-DNS strategies. It basically calls Globalping's API to get the resolution results for a domain in other regions, then picks the IP with the lowest ICMP latency and writes it to the local hosts file.
Code: Zhousiru/opti-hosts, Chinese README.md
Prebuilt binaries can be downloaded from Releases
Why
The TV at home connects to some overseas Emby media server. The Emby domain itself is configured with geo-split DNS to HK and US CDN nodes, but the connection still isn't great—evening peak-hour QoS is really bad, and I didn't want to burn through my proxy provider's traffic, so I set up a reverse proxy on an HK VPS, connected it via a tunnel to a mainland VPS as a relay, and then tunneled back home.
As it turned out, on the mainland the Emby domain resolved to an HK node (~60 ms), but on the HK VPS it resolved to a US node (~150 ms) Σヽ(゚Д ゚; )ノ
I don't know if that was configured that way on purpose... So I just put the HK CDN node's IP directly in the reverse proxy config and manually added the Host header. It worked great at first, but later the result was predictable: the IP stopped working, and I had to change it manually. That kind of periodic maintenance is way too much hassle.
So I threw together this little tool to automatically measure IPs and latency and update hosts. It's similar to "Cloudflare IP optimization", but this tool isn't limited to domains behind CF, and it doesn't have built-in CF CIDRs—it relies on Globalping to measure resolution results from various locations.
Fun little details
I had a wild idea to fold the tool's config into the existing hosts file, and tried using pest to define a tiny DSL called a hosts directive, something like this:
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
# OPTI-HOSTS example.com [Beijing, HK * 2, AS6939]
23.192.228.84 example.com
# 👆 这是生成的 hosts 记录
No extra config file needed—just run opti-hosts and it updates. Pretty clean, right? (x
(Though parsing with regex would be totally fine, I just wanted to try a parser generator 233)
Some limitations
Without logging in, Globalping limits each IP to creating at most 250 queries per hour; after logging in and providing a token, that can be raised to 500 (though the current version doesn't provide an option to set a token 233333).
Also, although I mentioned Cloudflare IP optimization, it works differently: Opti Hosts chooses IPs based solely on latency measured by ping, without considering factors like TCP latency or bandwidth (and it can't), but in most cases it should be fine and good enough.
Currently only prebuilt Linux versions for AMD64 & ARM64 are provided; Windows and macOS need to be built by yourself (flee)