From f3c36dad4ec3e17042741d475848bca913e48f3c Mon Sep 17 00:00:00 2001 From: terminaldweller Date: Tue, 17 Jan 2023 15:35:39 +0330 Subject: first commit --- icanhazallips.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 icanhazallips.go (limited to 'icanhazallips.go') diff --git a/icanhazallips.go b/icanhazallips.go new file mode 100644 index 0000000..bcca91e --- /dev/null +++ b/icanhazallips.go @@ -0,0 +1,54 @@ +// https://gist.github.com/miguelmota/7b765edff00dc676215d6174f3f30216 +package main + +import ( + "errors" + "log" + "net" + "net/http" + "strings" +) + +func getIP(r *http.Request) (string, error) { + ips := r.Header.Get("X-Forwarded-For") + splitIps := strings.Split(ips, ",") + + if len(splitIps) > 0 { + 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)) +} -- cgit v1.2.3