diff --git a/cidr.go b/cidr.go index f158844c..c68c7bc7 100644 --- a/cidr.go +++ b/cidr.go @@ -299,16 +299,21 @@ func IpAddresses(ipnet *net.IPNet) (ips chan string) { // IPToInteger converts an IP address to its integer representation. // It supports both IPv4 as well as IPv6 addresses. func IPToInteger(ip net.IP) (*big.Int, int, error) { - val := &big.Int{} - val.SetBytes([]byte(ip)) - - if len(ip) == net.IPv4len { - return val, 32, nil //nolint - } else if len(ip) == net.IPv6len { - return val, 128, nil //nolint - } else { - return nil, 0, fmt.Errorf("unsupported address length %d", len(ip)) + val := new(big.Int) + + // check if the ip is v4 => convert to 4 bytes representation + if ipv4 := ip.To4(); ipv4 != nil { + val.SetBytes(ipv4) + return val, 32, nil + } + + // check if the ip is v6 => convert to 16 bytes representation + if ipv6 := ip.To16(); ipv6 != nil { + val.SetBytes(ipv6) + return val, 128, nil } + + return nil, 0, fmt.Errorf("unsupported IP address format") } // IntegerToIP converts an Integer IP address to net.IP format. diff --git a/ip_test.go b/ip_test.go index 289c4c3b..e8249112 100644 --- a/ip_test.go +++ b/ip_test.go @@ -30,9 +30,9 @@ func TestIpEncodings(t *testing.T) { res = AlterIP(ip, []string{"4"}, 0, false) require.True(t, sliceutil.ContainsItems(res, []string{"0x7f.0x0.0x0.0x1", "0x7f000001"})) res = AlterIP(ip, []string{"5"}, 0, false) - require.Equal(t, []string{"281472812449793"}, res) + require.Equal(t, []string{"2130706433"}, res) res = AlterIP(ip, []string{"6"}, 0, false) - require.Equal(t, []string{"111111111111111101111111000000000000000000000001"}, res) + require.Equal(t, []string{"1111111000000000000000000000001"}, res) res = AlterIP(ip, []string{"7"}, 0, false) require.Equal(t, []string{"0x7f.0.0.0x1"}, res) res = AlterIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334", []string{"8"}, 0, false)