test IP primitives in proto buffer
This commit is contained in:
parent
7c5410441a
commit
b2b386b961
2 changed files with 46 additions and 0 deletions
|
|
@ -246,3 +246,21 @@ func (buf *LuxBuffer) WriteIPPort(addrPort netip.AddrPort) {
|
||||||
buf.WriteIP(addrPort.Addr())
|
buf.WriteIP(addrPort.Addr())
|
||||||
buf.WriteUint16(addrPort.Port())
|
buf.WriteUint16(addrPort.Port())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func LuxProtoIPToAddr(ip net.IP) netip.Addr {
|
||||||
|
if octets4 := ip.To4(); octets4 != nil {
|
||||||
|
return netip.AddrFrom4([4]byte(octets4))
|
||||||
|
} else {
|
||||||
|
return netip.AddrFrom16([16]byte(ip.To16()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func LuxProtoAddrToIP(addr netip.Addr) net.IP {
|
||||||
|
if addr.Is4() {
|
||||||
|
octets4 := addr.As4()
|
||||||
|
return octets4[:]
|
||||||
|
} else {
|
||||||
|
octets16 := addr.As16()
|
||||||
|
return octets16[:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ package tests
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"lux/proto"
|
"lux/proto"
|
||||||
|
"net"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -71,3 +72,30 @@ func TestReadOverrun(t *testing.T) {
|
||||||
t.Fatalf("no error when reading at offset 1 of 1 byte buffer\n")
|
t.Fatalf("no error when reading at offset 1 of 1 byte buffer\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIP(t *testing.T) {
|
||||||
|
ip4 := net.ParseIP("10.1.0.5")
|
||||||
|
ip6 := net.ParseIP("fd10:101::d47d:65ff:fe31:9367")
|
||||||
|
|
||||||
|
wd := proto.NewLuxBuffer()
|
||||||
|
wd.WriteIP(proto.LuxProtoIPToAddr(ip4))
|
||||||
|
wd.WriteIP(proto.LuxProtoIPToAddr(ip6))
|
||||||
|
|
||||||
|
rd := proto.FromSlice(wd.AllBytes())
|
||||||
|
|
||||||
|
newIp4, err := rd.ReadIP()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !proto.LuxProtoAddrToIP(newIp4).Equal(ip4) {
|
||||||
|
t.Fatalf("IPv4 does not equal: %v and %v", ip4.To4(), newIp4.AsSlice())
|
||||||
|
}
|
||||||
|
|
||||||
|
newIp6, err := rd.ReadIP()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !proto.LuxProtoAddrToIP(newIp6).Equal(ip6) {
|
||||||
|
t.Fatalf("IPv6 does not equal: %v and %v", ip4.To4(), newIp4.AsSlice())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue