Skip to content

Instantly share code, notes, and snippets.

@fyxme
Created June 1, 2023 14:20
Show Gist options
  • Save fyxme/8f81d3deee28d79f2f5df8c6d3e1adad to your computer and use it in GitHub Desktop.
Save fyxme/8f81d3deee28d79f2f5df8c6d3e1adad to your computer and use it in GitHub Desktop.
Golang webserver which echo's the request back to you and prints your IP address
package main
import (
"errors"
"log"
"net"
"net/http"
"strings"
"net/http/httputil"
"flag"
"strconv"
)
func getIP(r *http.Request) (string, error) {
ips := r.Header.Get("X-Forwarded-For")
log.Println("[.] X-Fowarded-For:",ips)
splitIps := strings.Split(ips, ",")
if len(splitIps) > 0 {
// this mght be wrong
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) {
log.Println("[!] New request received")
ip, err := getIP(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
w.WriteHeader(http.StatusOK)
lastHopIp, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
log.Println("[.] Original IP:", ip)
if ip == lastHopIp {
w.Write([]byte("Your ip is " + ip + "\n\n"))
} else {
log.Println("[.] Proxy IP:", lastHopIp)
w.Write([]byte("Your ip is " + ip + " and your request has been proxied via " + lastHopIp + "\n\n"))
}
requestDump, err := httputil.DumpRequest(r, true)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
w.Write(requestDump)
}
func isValidPort(p int) bool {
return (p > 0 && p < 65535)
}
func main() {
port := flag.Int("p", 80, "port to listen on")
flag.Parse()
portStr := strconv.Itoa(*port)
if !isValidPort(*port) {
log.Println("[?] Port", portStr, "is invalid")
return
}
log.Println("[-] Server starting on port", portStr)
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":"+portStr, nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment