IPv6對應的整形數字爲16個字節,只能用big.Int來存儲。而類似於“53174336847441874194254142093255507967”這種長度的數字可以由字符串來表示,如下代碼用於將數字字符串轉換爲對應的IPv6地址字符串。
相關文章:《Go語言:IPv6解析轉換成BigInt整形以及與IPv4的兼容》
package main
import (
"encoding/hex"
"errors"
"fmt"
"math/big"
"strings"
)
//NumToIPv6 converts a big integer represented by a string into an IPv6 address string
func NumToIPv6(numasstr string) (string, error) {
bi, ok := new(big.Int).SetString(numasstr, 10)
if !ok {
return "", errors.New("fail to convert string to big.Int")
}
b255 := new(big.Int).SetBytes([]byte{255})
var buf = make([]byte, 2)
p := make([]string, 8)
j := 0
var i uint
tmpint := new(big.Int)
for i = 0; i < 16; i += 2 {
tmpint.Rsh(bi, 120-i*8).And(tmpint, b255)
bytes := tmpint.Bytes()
if len(bytes) > 0 {
buf[0] = bytes[0]
} else {
buf[0] = 0
}
tmpint.Rsh(bi, 120-(i+1)*8).And(tmpint, b255)
bytes = tmpint.Bytes()
if len(bytes) > 0 {
buf[1] = bytes[0]
} else {
buf[1] = 0
}
p[j] = hex.EncodeToString(buf)
j++
}
return strings.Join(p, ":"), nil
}
func convertAndPrint(numasstr string) {
ipstr, _ := NumToIPv6(numasstr)
fmt.Printf("%s %v\n", ipstr, numasstr)
}
func main() {
convertAndPrint("53174336847441874194254142093255507967")
convertAndPrint("53174336768213711679990085974688268287")
convertAndPrint("0")
convertAndPrint("53174312128255169743780812907543003136")
convertAndPrint("65535")
convertAndPrint("167904045")
convertAndPrint("4294967295")
convertAndPrint("281470681743360")
convertAndPrint("281474976710655")
convertAndPrint("281470849647405")
}
輸出:
2801:0137:ffff:ffff:ffff:ffff:ffff:ffff 53174336847441874194254142093255507967
2801:0137:0000:0000:0000:ffff:ffff:ffff 53174336768213711679990085974688268287
0000:0000:0000:0000:0000:0000:0000:0000 0
2801:0000:0000:0000:0000:0000:0000:0000 53174312128255169743780812907543003136
0000:0000:0000:0000:0000:0000:0000:ffff 65535
0000:0000:0000:0000:0000:0000:0a02:032d 167904045
0000:0000:0000:0000:0000:0000:ffff:ffff 4294967295
0000:0000:0000:0000:0000:ffff:0000:0000 281470681743360
0000:0000:0000:0000:0000:ffff:ffff:ffff 281474976710655
0000:0000:0000:0000:0000:ffff:0a02:032d 281470849647405