简体   繁体   English

是否有内置的 function 来扩展 ipv6 地址?

[英]Is there an inbuilt function to expand ipv6 addresses?

I'm working on a project where I need to expand IPv6 addresses.我正在做一个需要扩展 IPv6 地址的项目。 Is there an inbuilt function in Go? Go里面有内置function吗?

What I'm currently doing is我目前正在做的是

ipv6 := "fe80:01::af0"
addr := net.ParseIP(ipv6)
fmt.Println(addr.String())

but this still prints但这仍然打印

fe80:01::af0

What I actually need is我真正需要的是

fe80:0001:0000:0000:0000:0000:0000:0af0

There's nothing in the standard library to do this, but it's easy to write your own function. 标准库中没有什么可以做的,但是编写自己的函数很容易。 One possible approach (of many): 一种(多种)可能的方法:

func FullIPv6(ip net.IP) string {
    dst := make([]byte, hex.EncodedLen(len(ip)))
    _ = hex.Encode(dst, ip)
    return string(dst[0:4]) + ":" +
        string(dst[4:8]) + ":" +
        string(dst[8:12]) + ":" +
        string(dst[12:16]) + ":" +
        string(dst[16:20]) + ":" +
        string(dst[20:24]) + ":" +
        string(dst[24:28]) + ":" +
        string(dst[28:])
}

Playground 操场

package main

import (
    "errors"
    "fmt"
    "net"
)

func expandIPv6Addr(s string) (string, error) {
    addr := net.ParseIP(s).To16()
    if addr == nil {
        return "", ErrInvalidAddress
    }

    var hex [16 * 3]byte
    for i := 0; i < len(addr); i++ {
        if i > 0 {
            hex[3*i-1] = ':'
        }
        hex[3*i] = nibbleToChar(addr[i] >> 4)
        hex[3*i+1] = nibbleToChar(addr[i])
    }

    return string(hex[:]), nil
}

func nibbleToChar(b byte) byte {
    b &= 0x0f
    if b > 9 {
        return ('a' - 10) + b
    }
    return '0' + b
}

var ErrInvalidAddress = errors.New("invalid address")

func main() {
    ipv6 := "fe80:01::af0"

    fmt.Println(ipv6)
    fmt.Println(expandIPv6Addr(ipv6))
}

Playground link . 游乐场链接

The IPAddress Go library can do this with one line of code. IPAddress Go 库可以用一行代码做到这一点。 Disclaimer: I am the project manager.免责声明:我是项目经理。

fmt.Print(ipaddr.NewIPAddressString("fe80:01::af0").GetAddress().ToFullString())

Output: Output:

fe80:0001:0000:0000:0000:0000:0000:0af0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM