Commit cda29e15 authored by Steven Allen's avatar Steven Allen

don't panic on 4byte IP addresses

They're valid.
parent 7f35106c
...@@ -115,22 +115,21 @@ func NetAddrToSockaddr(addr net.Addr) Sockaddr { ...@@ -115,22 +115,21 @@ func NetAddrToSockaddr(addr net.Addr) Sockaddr {
// IPAndZoneToSockaddr converts a net.IP (with optional IPv6 Zone) to a Sockaddr // IPAndZoneToSockaddr converts a net.IP (with optional IPv6 Zone) to a Sockaddr
// Returns nil if conversion fails. // Returns nil if conversion fails.
func IPAndZoneToSockaddr(ip net.IP, zone string) Sockaddr { func IPAndZoneToSockaddr(ip net.IP, zone string) Sockaddr {
switch { if ip4 := ip.To4(); ip4 != nil {
case len(ip) < net.IPv4len: // default to IPv4
buf := [4]byte{0, 0, 0, 0}
return &SockaddrInet4{Addr: buf}
case ip.To4() != nil:
var buf [4]byte var buf [4]byte
copy(buf[:], ip[12:16]) // last 4 bytes copy(buf[:], ip4) // last 4 bytes
return &SockaddrInet4{Addr: buf} return &SockaddrInet4{Addr: buf}
}
case ip.To16() != nil: if ip6 := ip.To16(); ip6 != nil {
var buf [16]byte var buf [16]byte
copy(buf[:], ip) copy(buf[:], ip6)
return &SockaddrInet6{Addr: buf, ZoneId: uint32(IP6ZoneToInt(zone))} return &SockaddrInet6{Addr: buf, ZoneId: uint32(IP6ZoneToInt(zone))}
} }
panic("should be unreachable") if len(ip) == 0 {
buf := [4]byte{0, 0, 0, 0}
return &SockaddrInet4{Addr: buf}
}
panic("invalid IP address")
} }
// IPAddrToSockaddr converts a net.IPAddr to a Sockaddr. // IPAddrToSockaddr converts a net.IPAddr to a Sockaddr.
......
package sockaddrnet
import (
"bytes"
"net"
"testing"
)
func assertIPEq(t *testing.T, ip net.IP, sa Sockaddr) {
switch s := sa.(type) {
case *SockaddrInet4:
if !bytes.Equal(s.Addr[:], ip.To4()) {
t.Error("IPs not equal")
}
case *SockaddrInet6:
if !bytes.Equal(s.Addr[:], ip.To16()) {
t.Error("IPs not equal")
}
default:
t.Error("not a known sockaddr")
}
}
func subtestIPSockaddr(t *testing.T, ip net.IP) {
assertIPEq(t, ip, IPAndZoneToSockaddr(ip, ""))
}
func TestIPAndZoneToSockaddr(t *testing.T) {
subtestIPSockaddr(t, net.ParseIP("127.0.0.1"))
subtestIPSockaddr(t, net.IPv4zero)
subtestIPSockaddr(t, net.IP(net.IPv4zero.To4()))
subtestIPSockaddr(t, net.IPv6unspecified)
assertIPEq(t, net.IPv4zero, IPAndZoneToSockaddr(nil, ""))
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment