Get client IP Address in Go
Knowing who is accessing your web server can be useful for tracking a user's activity. In this tutorial, we will learn how to get client IP address in Go.
To get the IP address of a client, just use
ip,_,_ := net.SplitHostPort(r.RemoteAddr)
However, sometimes the user access your web server via a proxy or load balancer ( such as in cloud hosting etc ) and the above code will give you the IP address of the proxy or load balancer.
To get the real IP address of the client, you can get the HTTP Request header information "X-Forwarded-For (XFF)"
fmt.Fprintf(w,"X-Forwarded-For :" + r.Header.Get("X-FORWARDED-FOR"));
This is the full code example that you can execute in your web server and test out with your web browser or curl.
client_ip.go
package main
import (
"fmt"
"net/http"
"net"
)
func IndexPage(w http.ResponseWriter, r *http.Request) {
// get client ip address
ip,_,_ := net.SplitHostPort(r.RemoteAddr)
// print out the ip address
fmt.Fprintf(w,ip + "\n\n")
// sometimes, the user acccess the web server via a proxy or load balancer.
// The above IP address will be the IP address of the proxy or load balancer and not the user's machine.
// let's get the request HTTP header "X-Forwarded-For (XFF)"
// if the value returned is not null, then this is the real IP address of the user.
fmt.Fprintf(w,"X-Forwarded-For :" + r.Header.Get("X-FORWARDED-FOR"));
}
func main() {
http.HandleFunc("/", IndexPage)
http.ListenAndServe(":8080", nil)
}
References:
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.2k Golang : Reset buffer example
+18.9k Golang : Populate dropdown with html/template example
+6k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+14.1k Golang : Parsing or breaking down URL
+6.4k Elasticsearch : Shutdown a local node
+6.4k Golang : Warp text string by number of characters or runes example
+6.9k Nginx : How to block user agent ?
+4.7k Unix/Linux : secure copying between servers with SCP command examples
+11.7k Golang : Sort and reverse sort a slice of runes
+10.9k CodeIgniter : How to check if a session exist in PHP?
+4.6k Golang : A program that contain another program and executes it during run-time
+5.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example