Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active October 31, 2024 19:22
Show Gist options
  • Save miguelmota/7b765edff00dc676215d6174f3f30216 to your computer and use it in GitHub Desktop.
Save miguelmota/7b765edff00dc676215d6174f3f30216 to your computer and use it in GitHub Desktop.
Golang get IP address from web HTTP request handler
package main
import (
"errors"
"log"
"net"
"net/http"
"strings"
)
// getIP returns the ip address from the http request
func getIP(r *http.Request) (string, error) {
ips := r.Header.Get("X-Forwarded-For")
splitIps := strings.Split(ips, ",")
if len(splitIps) > 0 {
// get last IP in list since ELB prepends other user defined IPs, meaning the last one is the actual client IP.
netIP := net.ParseIP(splitIps[len(splitIps)-1])
if netIP != nil {
return netIP.String(), nil
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}
netIP := net.ParseIP(ip)
if netIP != nil {
ip := netIP.String()
if ip == "::1" {
return "127.0.0.1", nil
}
return ip, nil
}
return "", errors.New("IP not found")
}
func handler(w http.ResponseWriter, r *http.Request) {
ip, err := getIP(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(ip))
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
@MohanVijayakumar
Copy link

MohanVijayakumar commented Mar 3, 2022

Hi,
Thanks for this, it helped me for get IP.
it seems , the if condition in line 16 not needed as splitIps always greater than 1
and also i think in x-forwarded-for header the left most is the client IP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment