Last active
October 25, 2022 15:18
-
-
Save kkirsche/ed0dd0fc7c044705fd1a56a7e1b1fa24 to your computer and use it in GitHub Desktop.
inet_aton and inet6_aton in Golang
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
package nessusProcessor | |
import ( | |
"encoding/hex" | |
"math/big" | |
"net" | |
) | |
// Inet_Aton converts an IPv4 net.IP object to a 64 bit integer. | |
func Inet_Aton(ip net.IP) int64 { | |
ipv4Int := big.NewInt(0) | |
ipv4Int.SetBytes(ip.To4()) | |
return ipv4Int.Int64() | |
} | |
// Inet6_Aton converts an IP Address (IPv4 or IPv6) net.IP object to a hexadecimal | |
// representaiton. This function is the equivalent of | |
// inet6_aton({{ ip address }}) in MySQL. | |
func Inet6_Aton(ip net.IP) string { | |
ipv4 := false | |
if ip.To4() != nil { | |
ipv4 = true | |
} | |
ipInt := big.NewInt(0) | |
if ipv4 { | |
ipInt.SetBytes(ip.To4()) | |
ipHex := hex.EncodeToString(ipInt.Bytes()) | |
return ipHex | |
} | |
ipInt.SetBytes(ip.To16()) | |
ipHex := hex.EncodeToString(ipInt.Bytes()) | |
return ipHex | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I made a full example and I update it to go1.18 netip (go doc says this package's Addr type takes less memory)
test.go