Recently I ran into an interesting problem. I needed to upload a small REST service to manage some hardware: all without human contact and with several network interfaces.
At a certain point, my system has to upload an auxiliary service and inform the client which IP and port he should access. Usually, this would be done with a config file somewhere, but one requirement is that I couldn’t guess my IP because it could come from any of the network interfaces, and leaving all this parameterized would be too complex.
The solution was to automate the whole process within my code, and for that, I needed to know both my IP and the client’s, so I would know which network to respond to, and so on.
As Go has a pretty good net library, I also wanted to support ipv6, and it’s not difficult. Just be careful to use what Go provides and not assume the IP and port format.
There are two functions from the net package that aren’t exported, so I copied them into my code to help parse the result.
The last function is to extract the last part of a string given a separator. In this case, we are using it to extract the zone in IPv6 addresses. This zone is usually the name of the network interface.
The splitHostZone function returns the host and the zone separately. If there is no zone, it will be an empty string. I need it because when I join the IP with the port again. I don’t want to include the zone.
Getting the server IP
There are several ways to find the server’s IP, but the simpler “Go style” I found was taking the address placed in the context of the request.
Getting the client’s IP, it’s easier because it’s already in the request, so it’s just handling the return as we did before.
Here is a gist with the example code.