Golang IPv4/IPv6转整型

TrumanWong
2/24/2022
TrumanWong

类型转换使用math/big

IPv4/IPv6转整型

func IP2Long(ipAddress string) *big.Int {
	ip := net.ParseIP(ipAddress)
	if ip == nil {
		return nil
	}
	isIPv6 := false
	for i := 0; i < len(ipAddress); i++ {
		switch ipAddress[i] {
		case '.':
			break
		case ':':
			isIPv6 = true
			break
		}
	}
	ipInt := big.NewInt(0)
	if isIPv6 {
		return ipInt.SetBytes(ip.To16())
	}
	return ipInt.SetBytes(ip.To4())
}

整型转IPv4/IPv6

// Long2Ip 整型转ip
func Long2Ip(ipLong *big.Int) string {
	ipByte := ipLong.Bytes()
	ip := net.IP(ipByte)
	return ip.String()
}

文中代码已上传github