ip

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2020 License: MIT Imports: 3 Imported by: 4

README

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

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

Contributors

Copyright (C) 2020 by Vikram Ingawale [GitHub]

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetClientIP

func GetClientIP(r *http.Request) string

GetClientIP - returns IP address string; The IP address if known, defaulting to empty string if unknown.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL