Files
ipv6calculator/main.go
2025-05-09 07:28:10 +02:00

97 lines
2.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"html/template"
"log"
"net"
"net/http"
)
const (
listenAddr = ":8080" // server port
ulaPrefix = "fdcb:7de3:a12a:0::" // fixed ULA /96 prefix
)
// pageTemplate is served for both GET (empty result) and POST (with result).
var pageTemplate = template.Must(template.New("page").Parse(`<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8"/>
<title>IPv4 → IPv6Mapper</title>
<style>
body { font-family: system-ui, sans-serif; margin: 2rem; }
form { display:flex; gap:.5rem; }
input[type=text] { flex:1; padding:.4rem; font-size:1rem; }
button { padding:.5rem 1rem; font-size:1rem; cursor:pointer; }
#result { margin-top:1.5rem; font-weight:bold; }
.error { color:#b00; }
</style>
</head>
<body>
<h1>IPv4 → IPv6Mapper</h1>
<form action="/convert" method="post">
<input type="text" name="ipv4" placeholder="172.29.0.0" value="{{.IPv4}}" required />
<button type="submit">Umrechnen</button>
</form>
{{if .IPv6}}
<div id="result">IPv6Adresse: <code>{{.IPv6}}</code></div>
{{end}}
{{if .Error}}
<div class="error">Fehler: {{.Error}}</div>
{{end}}
<p>Präfix: <code>` + ulaPrefix + `</code> &nbsp; (feste /96Zuordnung)</p>
</body>
</html>`))
// viewData transports data into the page template.
type viewData struct {
IPv4 string
IPv6 string
Error string
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Empty page on root
renderPage(w, viewData{})
})
http.HandleFunc("/convert", func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
renderPage(w, viewData{Error: "Ungültiges Formular"})
return
}
ipv4Str := r.FormValue("ipv4")
ipv6, err := embedIPv4(ipv4Str)
data := viewData{IPv4: ipv4Str}
if err != nil {
data.Error = err.Error()
} else {
data.IPv6 = ipv6
}
renderPage(w, data)
})
log.Printf("Server läuft auf http://localhost%s …", listenAddr)
log.Fatal(http.ListenAndServe(listenAddr, nil))
}
// embedIPv4 converts an IPv4 dotted string into the ulaPrefixbased IPv6 address.
func embedIPv4(ipv4 string) (string, error) {
ip := net.ParseIP(ipv4).To4()
if ip == nil {
return "", fmt.Errorf("'%s' ist keine gültige IPv4Adresse", ipv4)
}
first := uint16(ip[0])<<8 | uint16(ip[1]) // High 16 bits
second := uint16(ip[2])<<8 | uint16(ip[3]) // Low 16 bits
return fmt.Sprintf("%s%x:%x", ulaPrefix, first, second), nil
}
func renderPage(w http.ResponseWriter, d viewData) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := pageTemplate.Execute(w, d); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}