Golang 随机生成ipv4和ipv6

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

内容简介:我们知道在计算机中每一个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
}

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

查看所有标签

猜你喜欢:

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

The Lean Startup

The Lean Startup

Eric Ries / Crown Business / 2011-9-13 / USD 26.00

更多中文介绍:http://huing.com Most startups fail. But many of those failures are preventable. The Lean Startup is a new approach being adopted across the globe, chan ging the way companies are built and ......一起来看看 《The Lean Startup》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具