Skip to content

Commit

Permalink
Merge pull request #258 from hexagr/patch-2
Browse files Browse the repository at this point in the history
Update cidr.go
  • Loading branch information
Mzack9999 authored Nov 30, 2023
2 parents ef7c51c + ef9fb16 commit d8b431b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
23 changes: 14 additions & 9 deletions cidr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit d8b431b

Please sign in to comment.