Golang 随机生成ipv4和ipv6

栏目: Go · 发布时间: 6年前

内容简介:我们知道在计算机中每一个ipv4实际上都可以对应一个uint32的数,所以随机生成一些ip,实际上就是随机生成一些uint32的数。

随机生成ipv4

我们知道在计算机中每一个ipv4实际上都可以对应一个uint32的数,所以随机生成一些ip,实际上就是随机生成一些uint32的数。

type IPv4Int uint32

func (i IPv4Int) ip() net.IP {
    ip := make(net.IP, net.IPv6len)
    copy(ip, net.IPv4zero)
    binary.BigEndian.PutUint32(ip.To4(), uint32(i))
    return ip.To16()
}

func RandomIpv4Int() uint32 {
    return rand.New(rand.NewSource(time.Now().UnixNano())).Uint32()
}

随机生成ipv6

type IPv6Int [2]uint64 

func RandomIpv6Int() (result [2]uint64) {
    result[0] = rand.New(rand.NewSource(time.Now().UnixNano())).Uint64()
    result[1] = rand.New(rand.NewSource(time.Now().UnixNano())).Uint64()
    return result 
}

func RandomIPv6(num int) []string {
    result := make([]string, 0)
    for i := 0; i < num; i++ {
        ipInt := IPv6Int(RandomIpv6Int())
        ip := ipInt.ip()
        result = append(result, ip.String())
    }
    return result
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Inside the C++ Object Model

Inside the C++ Object Model

Stanley B. Lippman / Addison-Wesley Professional / 1996-5-13 / USD 64.99

Inside the C++ Object Model focuses on the underlying mechanisms that support object-oriented programming within C++: constructor semantics, temporary generation, support for encapsulation, inheritanc......一起来看看 《Inside the C++ Object Model》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具