Golang 随机生成ipv4和ipv6

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

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

The Mechanics of Web Handling

David R. Roisum

This unique book covers many aspects of web handling for manufacturing, converting, and printing. The book is applicable to any web including paper, film, foil, nonwovens, and textiles. The Mech......一起来看看 《The Mechanics of Web Handling》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具