Skip to content

This repository is used to get the client IP address of incoming HTTP requests in Go.

License

Notifications You must be signed in to change notification settings

vikram1565/request-ip

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Request - IP

This package is useful to get the client IP address of incoming HTTP requests in GoLang.

Inspired by Petar Bojinov

How It Works

It looks for specific headers in the request and falls back to some defaults if they do not exist.

The client ip is determined by the following order:

  1. X-Client-IP
  2. X-Forwarded-For (Header may return multiple IP addresses in the format:"clientIP, proxy1 IP, proxy2 IP", so we take the the first one.)
  3. CF-Connecting-IP (Cloudflare)
  4. Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function)
  5. True-Client-Ip (Akamai and Cloudflare)
  6. X-Real-IP (Nginx proxy/FastCGI)
  7. X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
  8. X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
  9. req.RemoteAddr

If an IP address cannot be found, it will return empty string.

Installation

Use the go command:

go get "github.com/vikram1565/request-ip"

Getting Started

package main

import (
	"log"
	"net/http"

	rip "github.com/vikram1565/request-ip"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		log.Println("Your client ip is ", rip.GetClientIP(r))
	})
	log.Println("server started on: http://127.0.1.1:8000")
	serverError := http.ListenAndServe(":8000", nil)
	if serverError != nil {
		log.Println("Failed to start server: ", serverError)
	}
}

on localhost you'll see ::1 or 127.0.0.1 if you're using IPv4 , ::ffff:127.0.0.1 if you're using IPv6

Output

Client IP

You may have noticed that when you browse to different domains, your browser is sending requests for http://<your.domain.com>/favicon.ico, behind the scenes. Thats why my log is printed twice.

Benchmarks

Benchmark

Links

  1. net/http
  2. http-headers
  3. remote address

Contributors

Copyright

Copyright (C) 2020 by Vikram Ingawale [GitHub]

request-ip package released under MIT License. See LICENSE for details.

About

This repository is used to get the client IP address of incoming HTTP requests in Go.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages