expand6/main.go

51 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-02-20 19:27:07 +01:00
// Lit stdin ligne par ligne, et remplace toutes les IPv6 lues sur la ligne par leur equivalent
// en affichant tous les bits
// Ex: 'ceci est une ipv6 : dead:beef::1' => 'ceci est une ipv6 : dead:beef:0000:0000:0000:0000:0000:00001'
//
package main
import (
"os"
"fmt"
"bufio"
"errors"
"regexp"
"strings"
"net/netip"
)
var ErrInvalidAddress = errors.New("invalid address")
func main() {
var dest []string
var newline string
// From https://stackoverflow.com/a/17871737
regexv6 := `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))`
regex := regexp.MustCompile(regexv6)
reader := bufio.NewReader(os.Stdin)
for {
dest = dest[:0]
line, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("%v\n", err)
return
}
newline = line
src := regex.FindAllString(line, -1)
if len(src) > 0 {
for _, s := range src {
addr, _ := netip.ParseAddr(s)
dest = append(dest, addr.StringExpanded())
}
for i, s := range src {
newline = strings.Replace(newline, s, dest[i], 1)
}
}
fmt.Printf(newline)
}
return
}