Go randIPBetween()

1 개요[ | ]

Go randIPBetween()
package main

import (
	"encoding/binary"
	"fmt"
	"math/rand"
	"net"
	"time"
)

func randIPBetween(ipString1, ipString2 string) string {
	ipInt := randBetween(ip2int(ipString1), ip2int(ipString2))
	return int2ip(ipInt)
}

func randBetween(min, max int) int {
	return rand.Intn(max-min+1) + min
}

func ip2int(ipString string) int {
	ip := net.ParseIP(ipString)
	if ip == nil {
		return -1
	}
	return int(binary.BigEndian.Uint32(ip.To4()))
}

func int2ip(ipInt int) string {
	if ipInt < 0 || ipInt > 4294967295 {
		return ""
	}
	ip := make(net.IP, 4)
	binary.BigEndian.PutUint32(ip, uint32(ipInt))
	return ip.String()
}

func main() {
	rand.Seed(time.Now().UnixNano())

	fmt.Println(randIPBetween("10.0.0.0", "10.0.0.1"))
	fmt.Println(randIPBetween("10.0.0.0", "10.0.0.1"))
	fmt.Println(randIPBetween("10.0.0.0", "10.0.0.1"))
	fmt.Println(randIPBetween("10.0.0.0", "10.0.0.1"))
	fmt.Println(randIPBetween("10.0.0.0", "10.0.0.1"))
	fmt.Println(randIPBetween("10.0.0.0", "10.0.0.1"))

	fmt.Println(randIPBetween("192.168.0.0", "192.168.255.255"))
	fmt.Println(randIPBetween("192.168.0.0", "192.168.255.255"))
	fmt.Println(randIPBetween("192.168.0.0", "192.168.255.255"))
	fmt.Println(randIPBetween("192.168.0.0", "192.168.255.255"))
	fmt.Println(randIPBetween("192.168.0.0", "192.168.255.255"))
	fmt.Println(randIPBetween("192.168.0.0", "192.168.255.255"))
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}