Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang ip <-> int conversion
func ip2int(ip net.IP) uint32 {
if len(ip) == 16 {
return binary.BigEndian.Uint32(ip[12:16])
}
return binary.BigEndian.Uint32(ip)
}
func int2ip(nn uint32) net.IP {
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, nn)
return ip
}
@srPuebla

This comment has been minimized.

Copy link

@srPuebla srPuebla commented Jun 15, 2020

Could you provide 2 similar functions for IPV6?

Thanks!

@ammario

This comment has been minimized.

Copy link
Owner Author

@ammario ammario commented Jun 15, 2020

There's no native 16 byte integer in Go, so unfortunately it wouldn't make too much sense. You could replace the 4 with 16 and use math/big.Int instead of ints if you are committed.

@srPuebla

This comment has been minimized.

Copy link

@srPuebla srPuebla commented Jun 15, 2020

Yeah, i got it. I put it here for future adventurers of GO

func ipv6ToInt(IPv6Addr net.IP) *big.Int {
    IPv6Int := big.NewInt(0)
    IPv6Int.SetBytes(IPv6Addr)
    return IPv6Int
} 
func IntToIpv6(intipv6 *big.Int) net.IP {
    ip := intipv6.Bytes()
    var a net.IP = ip
    return a
}

Regards

@trashbo4t

This comment has been minimized.

Copy link

@trashbo4t trashbo4t commented Jun 25, 2020

Yeah, i got it. I put it here for future adventurers of GO

func ipv6ToInt(IPv6Addr net.IP) *big.Int {
    IPv6Int := big.NewInt(0)
    IPv6Int.SetBytes(IPv6Addr)
    return IPv6Int
} 
func IntToIpv6(intipv6 *big.Int) net.IP {
    ip := intipv6.Bytes()
    var a net.IP = ip
    return a
}

Regards

For the second conversion, could you not just do:

func IntToIpv6(intipv6 *big.Int) net.IP {
   return net.IP(intipv6.Bytes())
}

or even

func IntToIpv6(intipv6 *big.Int) net.IP {
   return intipv6.Bytes()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.