When doing research on peer-to-peer networks, addressing can become pretty complex pretty quickly. Not everyone has the resources to allocate static, public facing IP addresses to machines. A machine that is in a home network for example only has a single public-facing IP address, usually assigned to the router. The router then performs NAT (network address translation) forwarding requests to internal devices.
In order to get a service running on an internal network, you can port forward external requests to a specific port to a specific device. Requests are made to the router’s IP address, and the router passes it on. But how do you know the IP address of the device? Moreover, what happens if the router is assigned a new IP address? Static IP addresses generally cost more.
It seems like services such as DynDNS and DDNS are no longer a default on the routers that are being shipped with broadband services like Xfinity or Fios. I therefore had to create my own, using the excellent service provided by myexternalip.com. The wrapper in Go is as follows:
When making a request to an external server like myexternalip.com, the public IP address of the router is used in the connection. The external server therefore can respond with what it sees as your public facing IP address, and that’s exactly what happens here.
I tried to make the PublicIP()
function a bit robust, using a timeout of 5 seconds so it couldn’t hang up any calling programs, and performing a lot of error handling. For example, a 429 response from myexternalip.com means that the rate limit has been exceeded (30 requests per minute). As I like the service, I wanted to make sure this was maintained so I ensured an error was thrown if this was breached. Additionally I used the json
format rather than the raw
format which meant I had to do some parsing, but I think it lends the code a bit more stability.
If you’re looking for a raw option, check out: get_external_ip.go. But I hope you see that my version is a tad more robust.