记录一下ipv4和ipv6与int互转通用处理方式,由于ipv6转的int比较大,因此需要使用big.Int来保存
package main
import (
"fmt"
"math/big"
"net/netip"
)
func InetNtoA(ip *big.Int, ipv4 int64) string {
if ip == nil {
ip = new(big.Int).SetInt64(ipv4)
}
addr, ok := netip.AddrFromSlice(ip.Bytes())
if ok {
return addr.String()
}
return ""
}
func InetAtoN(ip string) (*big.Int, int64, error) {
addr, err := netip.ParseAddr(ip)
if err != nil {
return nil, 0, err
}
// ipv4和ipv6分两种情况,使调用方知道返回类型
ipInt := new(big.Int).SetBytes(addr.AsSlice())
if addr.Is4() {
return nil, ipInt.Int64(), nil
}
return ipInt, 0, nil
}
func main() {
ipv6 := "fe80::21b:77ff:fbd6:7860"
ipInt, ipv4, err := InetAtoN(ipv6)
if err != nil {
panic(err)
}
fmt.Println(ipInt, ipv4, InetNtoA(ipInt, ipv4))
ip := "192.168.78.123"
ipInt, ipv4, err = InetAtoN(ip)
if err != nil {
panic(err)
}
fmt.Println(ipInt, ipv4, InetNtoA(ipInt, ipv4))
}
标签:err,nil,int,ip,ipInt,ipv4,ipv6,互转
From: https://www.cnblogs.com/janbar/p/16860808.html