meshname/whoami.go
2024-06-14 03:49:28 +00:00

52 lines
1.4 KiB
Go

package main
import (
"net/http"
"net"
"encoding/base32"
"strings"
"flag"
)
// define tld
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"}, "")
return domain
}
// handle HTTP requests
func handler(w http.ResponseWriter, r *http.Request) {
ip, port, err := net.SplitHostPort(r.RemoteAddr)
_, _ = port, err
parsedIP := net.ParseIP(ip)
// return domain for IPv6 only
if parsedIP.To4() == nil {
w.Write([]byte(domainFromIP(parsedIP)))
} else {
// set the response status code to 422
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte("ipv4 not supported\n"))
}
}
func main() {
// define path
http.HandleFunc("/", handler)
// define ip address
address := flag.String("address", "[::0]", "The interface address to listen on")
// define port
port := flag.String("port", "8008", "The port to listen on")
// parse the command-line arguments
flag.Parse()
// construct listening address
listenAddr := strings.Join([]string{*address, ":", *port}, "")
print("Listening on address: ", listenAddr, "\n")
// start server
http.ListenAndServe(listenAddr, nil)
}