Extract the real HTTP client's Remote IP Address.
The only requirement is the Go Programming Language.
$ go get github.com/kataras/realip
The main function is Get
, it makes use of the Default
options to extract the request's remote address.
package main
import (
"fmt"
"net/http"
"github.com/kataras/realip"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
ip := realip.Get(r)
fmt.Fprintf(w, "Your Public IPv4 is: %s", ip)
}
The
Get(r)
function calls theDefault.Get(r)
method
Here are the default values:
var Default = Options{
Headers: []string{
"X-Real-Ip",
"X-Forwarded-For",
"CF-Connecting-IP",
},
PrivateSubnets: []Range{
{
Start: net.ParseIP("10.0.0.0"),
End: net.ParseIP("10.255.255.255"),
},
{
Start: net.ParseIP("100.64.0.0"),
End: net.ParseIP("100.127.255.255"),
},
{
Start: net.ParseIP("172.16.0.0"),
End: net.ParseIP("172.31.255.255"),
},
{
Start: net.ParseIP("192.0.0.0"),
End: net.ParseIP("192.0.0.255"),
},
{
Start: net.ParseIP("192.168.0.0"),
End: net.ParseIP("192.168.255.255"),
},
{
Start: net.ParseIP("198.18.0.0"),
End: net.ParseIP("198.19.255.255"),
},
},
}
Use the AddRange
method helper to add an IP range in custom options:
func main() {
myOptions := &realip.Options{Headers: []string{"X-Forwarded-For"}}
myOptions.AddRange("192.168.0.0", "192.168.255.255")
// [...]
http.HandleFunc("/", handler(myOptions))
}
func handler(opts *realip.Options) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request){
ip := opts.Get(r)
// [...]
}
}
Please navigate through _examples directory for more.
This software is licensed under the MIT License.