Commit aabd5dc7 authored by Steven Allen's avatar Steven Allen

cleaner ip to sockaddr conversion

1. Never panic.
2. Only return a unspecified address if the IP is nil (no other random error
cases).
3. Simplify the logic.
parent 6ab77f67
...@@ -115,26 +115,29 @@ func NetAddrToSockaddr(addr net.Addr) Sockaddr { ...@@ -115,26 +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 {
if zone != "" { // Unspecified?
var buf [16]byte if ip == nil {
copy(buf[:], ip.To16()) if zone != "" {
return &SockaddrInet6{Addr: buf, ZoneId: uint32(IP6ZoneToInt(zone))} return &SockaddrInet6{ZoneId: uint32(IP6ZoneToInt(zone))}
}
return new(SockaddrInet4)
} }
if ip4 := ip.To4(); ip4 != nil {
// Valid IPv4?
if ip4 := ip.To4(); ip4 != nil && zone == "" {
var buf [4]byte var buf [4]byte
copy(buf[:], ip4) // last 4 bytes copy(buf[:], ip4) // last 4 bytes
return &SockaddrInet4{Addr: buf} return &SockaddrInet4{Addr: buf}
} }
// Valid IPv6 address?
if ip6 := ip.To16(); ip6 != nil { if ip6 := ip.To16(); ip6 != nil {
var buf [16]byte var buf [16]byte
copy(buf[:], ip6) copy(buf[:], ip6)
return &SockaddrInet6{Addr: buf, ZoneId: uint32(IP6ZoneToInt(zone))} return &SockaddrInet6{Addr: buf, ZoneId: uint32(IP6ZoneToInt(zone))}
} }
if len(ip) == 0 {
buf := [4]byte{0, 0, 0, 0} return nil
return &SockaddrInet4{Addr: buf}
}
panic("invalid IP address")
} }
// IPAddrToSockaddr converts a net.IPAddr to a Sockaddr. // IPAddrToSockaddr converts a net.IPAddr to a Sockaddr.
......
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