Skip to content

kataras/realip

Repository files navigation

Real IP

build status report card godocs

Extract the real HTTP client's Remote IP Address.

Installation

The only requirement is the Go Programming Language.

$ go get github.com/kataras/realip

Getting Started

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 the Default.Get(r) method

Options

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.

License

This software is licensed under the MIT License.