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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM