Which package to use to get the real IP of the client?

I’m undecided, I want to identify the request of a client, and what better than using the IP, but looking at my options I don’t know which one is more reliable:

Native option with the net package:

func PrintIP(l net.Listener) {
	fmt.Println(fmt.Sprintf("<%s> %s", l.Addr().Network(), l.Addr().String()))
}

External option with github.com/tomasen/realip package:

func PrintIP(r *http.Request) {
	fmt.Println(realip.FromRequest(r))
}

Does net.Listener keep the real IP of the client? Because if so I prefer to use that option but if not, then I guess it is best to use realip.FromRequest or is there a better suggestion?.

net.Listener works for getting the IP for arbitrary connections, while realip.FromRequest works for HTTP, but will very likely give you the IP of the real client, not the IP of the proxy it uses. Though this IP can in theory be from a private network, also not all proxies set the headers that would tell you the original IP.

At the end it depends on your usecase.

2 Likes