Skip to content

Commit

Permalink
Update cidr.go
Browse files Browse the repository at this point in the history
Currently, the "-ip-format" flag for case 5 does not properly work. For example, as reflected in ticket 221, the command `echo '127.0.0.1' | mapcidr -ip-format 5` incorrectly returns the value `281472812449793` when it should return the value 
`2130706433`

This pull request fixes the function "IPToInteger" to correctly convert both IPv4 and IPv6 addresses to their respective integer representations.
  • Loading branch information
hexagr authored Oct 20, 2023
1 parent bc73deb commit 2933c15
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions cidr.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,18 +299,23 @@ 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)

if ipv4 := ip.To4(); ipv4 != nil { // Iff ipv4, convert to 4 byte representation
val.SetBytes(ipv4)
return val, 32, nil
}

if ipv6 := ip.To16(); ipv6 != nil { // Iff ipv6, convert to 16 byte representation
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.
func IntegerToIP(ipInt *big.Int, bits int) net.IP {
ipBytes := ipInt.Bytes()
Expand Down

0 comments on commit 2933c15

Please sign in to comment.