Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update cidr.go #258

Merged
merged 5 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading