Last active
November 15, 2022 13:38
-
-
Save j2L4e/a83dbe97824db086ae4350f1978ba2f3 to your computer and use it in GitHub Desktop.
get a random ip within a provided subnet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # https://gist.github.com/jjarmoc/1299906 | |
| function atoi { | |
| #Returns the integer representation of an IP arg, passed in ascii dotted-decimal notation (x.x.x.x) | |
| IP=$1; IPNUM=0 | |
| for (( i=0 ; i<4 ; ++i )); do | |
| ((IPNUM+=${IP%%.*}*$((256**$((3-${i})))))) | |
| IP=${IP#*.} | |
| done | |
| echo $IPNUM | |
| } | |
| # https://gist.github.com/jjarmoc/1299906 | |
| function itoa { | |
| #returns the dotted-decimal ascii form of an IP arg passed in integer format | |
| echo -n $(($(($(($((${1}/256))/256))/256))%256)). | |
| echo -n $(($(($((${1}/256))/256))%256)). | |
| echo -n $(($((${1}/256))%256)). | |
| echo $((${1}%256)) | |
| } | |
| function rnd_ip() { | |
| NET_ADDR=$1 | |
| NET_MASK=$2 | |
| NET_INT=$(atoi $NET_ADDR) | |
| IP_INT=$(($NET_INT + 1 + $RANDOM % $((2 ** $(( 32 - $NET_MASK)))) )) | |
| IP=$(itoa $IP_INT) | |
| echo $IP | |
| } | |
| #usage: rnd_ip 10.0.0.0 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment