diff --git a/bytesconv.go b/bytesconv.go index 4e36d1d7b3..a44e226221 100644 --- a/bytesconv.go +++ b/bytesconv.go @@ -73,15 +73,11 @@ func ParseIPv4(dst net.IP, ipStr []byte) (net.IP, error) { if len(ipStr) == 0 { return dst, errEmptyIPStr } - if len(dst) < net.IPv4len { + if len(dst) < net.IPv4len || len(dst) > net.IPv4len { dst = make([]byte, net.IPv4len) } copy(dst, net.IPv4zero) dst = dst.To4() - if dst == nil { - // developer sanity-check - panic("BUG: dst must not be nil") - } b := ipStr for i := 0; i < 3; i++ { diff --git a/bytesconv_test.go b/bytesconv_test.go index 54e5e20022..d5ca5e4341 100644 --- a/bytesconv_test.go +++ b/bytesconv_test.go @@ -59,21 +59,27 @@ func testAppendHTMLEscape(t *testing.T, s, expectedS string) { func TestParseIPv4(t *testing.T) { t.Parallel() - testParseIPv4(t, "0.0.0.0", true) - testParseIPv4(t, "255.255.255.255", true) - testParseIPv4(t, "123.45.67.89", true) + testParseIPv4(t, net.IP{0}, "0.0.0.0", true) + testParseIPv4(t, nil, "0.0.0.0", true) + testParseIPv4(t, net.IP{0, 0, 0, 0, 0}, "0.0.0.0", true) + testParseIPv4(t, nil, "255.255.255.255", true) + testParseIPv4(t, nil, "123.45.67.89", true) // ipv6 shouldn't work - testParseIPv4(t, "2001:4860:0:2001::68", false) + testParseIPv4(t, nil, "2001:4860:0:2001::68", false) // invalid ip - testParseIPv4(t, "foobar", false) - testParseIPv4(t, "1.2.3", false) - testParseIPv4(t, "123.456.789.11", false) + testParseIPv4(t, nil, "", false) + testParseIPv4(t, nil, "foobar", false) + testParseIPv4(t, nil, "1.2.3", false) + testParseIPv4(t, nil, "123.456.789.11", false) + testParseIPv4(t, nil, "b.1.2.3", false) + testParseIPv4(t, nil, "1.2.3.b", false) + testParseIPv4(t, nil, "1.2.3.456", false) } -func testParseIPv4(t *testing.T, ipStr string, isValid bool) { - ip, err := ParseIPv4(nil, []byte(ipStr)) +func testParseIPv4(t *testing.T, dst net.IP, ipStr string, isValid bool) { + ip, err := ParseIPv4(dst, []byte(ipStr)) if isValid { if err != nil { t.Fatalf("unexpected error when parsing ip %q: %v", ipStr, err)