golang IPv6 转 十进制
IPv4 互换:
package main import ( "fmt" "math/big" "net" ) func InetNtoA(ip int64) string { return fmt.Sprintf("%d.%d.%d.%d", byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip)) } func InetAtoN(ip string) int64 { ret := big.NewInt(0) ret.SetBytes(net.ParseIP(ip).To4()) return ret.Int64() } func main() { ip := "192.168.78.123" ipInt := InetAtoN(ip) fmt.Printf("convert string ip [%s] to int: %d\n", ip, ipInt) fmt.Printf("convert int ip [%d] to string: %s\n", ipInt, InetNtoA(ipInt)) }
IPv6互换:
package main import ( "fmt" "math/big" "net" ) func IP6toInt(IPv6Address net.IP) *big.Int { IPv6Int := big.NewInt(0) IPv6Int.SetBytes(IPv6Address.To16()) return IPv6Int } func main() { ipv6 := "2001:db8:0:1::101" ipv6Decimal := IP6toInt(net.ParseIP(ipv6)) fmt.Println(ipv6Decimal) }
测试结果:
[root@wangjq]# go run 111.go 42540766411282592875350729025363378433