add ip=true optional parameter

This commit is contained in:
cynic 2024-08-08 14:54:19 +00:00
parent 46b3388b83
commit 507b16fbd0

View File

@ -6,6 +6,7 @@ import (
"encoding/base32"
"strings"
"flag"
"log"
)
// define tld
@ -14,12 +15,17 @@ var tld = flag.String("tld", "mesh.cat", "The top level domain for our network")
// domainFromIP derives a meshname subdomain for the authoritative DNS server address
func domainFromIP(target net.IP) string {
host := strings.ToLower(base32.StdEncoding.EncodeToString(target)[0:26])
domain := strings.Join([]string{host, ".", *tld, "\n"}, "")
domain := host + "." + *tld
return domain
}
// handle HTTP requests
func handler(w http.ResponseWriter, r *http.Request) {
// parse query parameters
params := r.URL.Query()
ipParam := params.Get("ip")
// check if the "ip" query parameter is set to "true"
showIP := ipParam == "true"
// get client's ip address
ip, port, err := net.SplitHostPort(r.RemoteAddr)
_, _ = port, err
@ -31,7 +37,13 @@ func handler(w http.ResponseWriter, r *http.Request) {
parsedIP := net.ParseIP(ip)
// return domain for IPv6 only
if parsedIP.To4() == nil {
w.Write([]byte(domainFromIP(parsedIP)))
if (showIP) {
w.Write([]byte(ip + "\n"))
} else {
w.Write([]byte(domainFromIP(parsedIP) + "\n"))
}
log.Println(showIP)
log.Println(ip)
} else {
// set the response status code to 422
w.WriteHeader(http.StatusUnprocessableEntity)
@ -49,7 +61,7 @@ func main() {
// parse the command-line arguments
flag.Parse()
// construct listening address
listenAddr := strings.Join([]string{*address, ":", *port}, "")
listenAddr := *address + ":" + *port
print("Listening on address: ", listenAddr, "\n")
// start server
http.ListenAndServe(listenAddr, nil)