Last active
February 7, 2025 05:24
-
-
Save ammario/649d4c0da650162efd404af23e25b86b to your computer and use it in GitHub Desktop.
Golang IP <-> int conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
@wilrodriguez I didn't realize how popular this gist was and recklessly updated it. I reverted it back per your message. Thank you!
Really helpful!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm surprised no one has mentioned it yet, but this latest change actually breaks the code. The length of both ipv4 and ipv6 addresses in
net.IP
representation is 16 bytes due the data structure being designed to accommodate both types of addresses. As proof of this point, see the following unit test:This test results in the following output:
I've come up with this alternative implementation that depends on
net.IP
'sTo4()
method, which returnsnil
for anything that's not a valid v4 IP.Note that my implementation does return error, so, if you need a function that only returns a single value, you can always change to a panic like the original function, but I personally like returning an error better.