0x00 问题描述

An IP is a single IP address, a slice of bytes. Functions in this package accept either 4-byte (IPv4) or 16-byte (IPv6) slices as input.
GO的net库接受以4字节或16字节切片组成的IPv4和IPv6地址

Note that in this documentation, referring to an IP address as an IPv4 address or an IPv6 address is a semantic property of the address, not just the length of the byte slice: a 16-byte slice can still be an IPv4 address.
已知IPv4单位最大255,占8-bit,也就是1-byte,一共占4位,公共就是4-byte。
而IPv6地址单位最大65535占2-byte,一共8位,总共占16-byte.
所以无论是IPv4还是IPv6,一个16-byte长度的切片足以存储上述IP地址。所以go语言net库的IP地址是一16-byte大小的切片储存的。

0x01 问题分析

由于Go语言以16-byte大小的切片储存IP地址,在不知道地址类型是IPv4还是IPv6的情况下,自带string函数是无法直接将byte切片转化为string。这个时候就绪要遍历整个表取出对应的byte。这里我只需要IPv4的地址那么只需要取出ipAddr[12:15]即可,使用sprintf函数添加'.'分隔符组成string.

0x02 Go代码

addr,err := net.LookupIP("www.kawanoii.cn")  //解析此域名对应的ip,存储到addr (此变量类型为[]net.IP)
if err != nil {
    fmt.Printf("解析错误:无法解析: %s \n",AddressToBoost)
    continue
} else {
    fmt.Printf("自动解析:%s > %s \n", AddressToBoost,addr)
    ipAddressToBoost = fmt.Sprintf("%d.%d.%d.%d/24",addr[0][12],addr[0][13],addr[0][14],addr[0][15])
    //fmt.Printf("IP合并:%s \n",ipAddressToBoost)
}

https://golang.org/pkg/net/#IP

标签: Golang

评论已关闭