Unverified Commit 09ae6064 authored by Steven Allen's avatar Steven Allen Committed by GitHub

Merge pull request #10 from libp2p/fix/4byte-ip

don't panic on 4byte IP addresses
parents 7f35106c aabd5dc7
...@@ -115,22 +115,29 @@ func NetAddrToSockaddr(addr net.Addr) Sockaddr { ...@@ -115,22 +115,29 @@ 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 { // Unspecified?
case len(ip) < net.IPv4len: // default to IPv4 if ip == nil {
buf := [4]byte{0, 0, 0, 0} if zone != "" {
return &SockaddrInet4{Addr: buf} return &SockaddrInet6{ZoneId: uint32(IP6ZoneToInt(zone))}
}
return new(SockaddrInet4)
}
case ip.To4() != nil: // Valid IPv4?
if ip4 := ip.To4(); ip4 != nil && zone == "" {
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: // Valid IPv6 address?
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")
return nil
} }
// 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