fix ip parsing

This commit is contained in:
Balakrishnan Balasubramanian 2023-04-10 14:16:23 -04:00
parent 8eeca16d99
commit 91eadc80e0
2 changed files with 31 additions and 6 deletions

10
main.go
View File

@ -26,6 +26,8 @@ var (
) )
func genRecord() (libdns.Record, error) { func genRecord() (libdns.Record, error) {
ipv4 := ip.To4()
ipv6 := ip.To16()
switch { switch {
case cname != "": case cname != "":
return libdns.Record{ return libdns.Record{
@ -33,17 +35,17 @@ func genRecord() (libdns.Record, error) {
Name: sub, Name: sub,
Value: cname, Value: cname,
}, nil }, nil
case len(ip) == net.IPv4len: case ipv4 != nil:
return libdns.Record{ return libdns.Record{
Type: "A", Type: "A",
Name: sub, Name: sub,
Value: ip.To4().String(), Value: ipv4.String(),
}, nil }, nil
case len(ip) == net.IPv6len: case ipv6 != nil:
return libdns.Record{ return libdns.Record{
Type: "AAAA", Type: "AAAA",
Name: sub, Name: sub,
Value: ip.To16().String(), Value: ipv6.String(),
}, nil }, nil
} }
return libdns.Record{}, fmt.Errorf("neither cname nor valid ip is set") return libdns.Record{}, fmt.Errorf("neither cname nor valid ip is set")

View File

@ -2,6 +2,7 @@ package main
import ( import (
"fmt" "fmt"
"net"
"testing" "testing"
) )
@ -9,7 +10,29 @@ func TestParseRange(t *testing.T) {
expected := []int{0, 1, 2, 6} expected := []int{0, 1, 2, 6}
actual := parseRange("0-2,-5,6,-7-7,1, 11", 10) actual := parseRange("0-2,-5,6,-7-7,1, 11", 10)
if fmt.Sprint(expected) != fmt.Sprint(actual) { if fmt.Sprint(expected) != fmt.Sprint(actual) {
fmt.Printf("unexpected %#v\n", actual) t.Errorf("unexpected %#v\n", actual)
t.Fail() }
}
func TestParseIP(t *testing.T) {
var ip net.IP
if err := ip.UnmarshalText([]byte("127.0.0.1")); err != nil {
t.Error(err)
}
if ip.To4() == nil {
t.Error("Failed to parse ipv4")
}
if ip.To16() == nil {
t.Error("Failed to parse as ipv6")
}
if err := ip.UnmarshalText([]byte("::1")); err != nil {
t.Error(err)
}
if ip.To16() == nil {
t.Error("Failed to parse ipv6")
}
if ip.To4() != nil {
t.Error("ipv6 parsed as ipv4")
} }
} }