Skip to content

Instantly share code, notes, and snippets.

@Sy14r
Created April 6, 2020 15:11
Show Gist options
  • Save Sy14r/1d605445ace43e297b431cbb3346bb9c to your computer and use it in GitHub Desktop.
Save Sy14r/1d605445ace43e297b431cbb3346bb9c to your computer and use it in GitHub Desktop.
function Get-RandomIP {
<#
.SYNOPSIS
Function to generate random IPs.
.DESCRIPTION
Generate Random IPs with optional ability to target public/private IP space
.PARAMETER ExcludePrivate
Specifies to exclude IANA reserved IP addresses (see: https://en.wikipedia.org/wiki/Reserved_IP_addresses) (default: false)
.PARAMETER ExcludePublic
Specifies to exclude publicly routable IP addresses (see: https://en.wikipedia.org/wiki/Reserved_IP_addresses) (default: false)
.PARAMETER Count
Number of IPs to generate (default: 1)
.EXAMPLE
PS C:\> Get-RandomIP
Generates a single publicly routable IPv4 addressd
.EXAMPLE
PS C:\> Get-RandomIP -Count 2000
Generates 2000 publicly routable IPv4 addressd
#>
param(
[Switch]
$ExcludePrivate,
[Switch]
$ExcludePublic,
[String]
$Count
)
## Declare helper function to check an IP and see if it is private
function Get-IsPrivate{
param(
[String]
$Address
)
$octets = $Address -split "\."
if($Address -eq "255.255.255.255"){
return $true
}
if($octets[0] -eq "0"){
return $true
}
if($octets[0] -eq "10"){
return $true
}
if($octets[0] -eq "127"){
return $true
}
if($octets[0] -in (224..239)){
return $true
}
if($octets[0] -in (240..255)){
return $true
}
if($octets[0] -eq "100"){
if($octets[1] -in (64..127)){
return $true
}
}
if($octets[0] -eq "169"){
if($octets[1] -eq "254"){
return $true
}
}
if($octets[0] -eq "172"){
if($octets[1] -in (16..31)){
return $true
}
}
if($Address -match "192\.88\.99\.*"){
return $true
}
if($Address -match "192\.168\.*\.*"){
return $true
}
if($Address -match "198\.18\.*\.*"){
return $true
}
if($Address -match "198\.19\.*\.*"){
return $true
}
if($Address -match "198\.51\.100\.*"){
return $true
}
if($Address -match "203\.0\.113\.*"){
return $true
}
return $false
}
## Set count to default value
if(!$Count){
$Count = 1
}
$continue = $true
## Sanity check that we can generate IPs based off user supplied switches...
if($ExcludePrivate -and $ExcludePublic){
Write-Host "You cannot exclude both Public and Private IP address space"
$Count = 0
}
while($Count -gt 0){
$octetValues = (0..255)
$o1 = $octetValues | Get-Random
$o2 = $octetValues | Get-Random
$o3 = $octetValues | Get-Random
$o4 = $octetValues | Get-Random
if($o1 -ne 0){
$isPriv = Get-IsPrivate -Address "$o1.$o2.$o3.$o4"
if($ExcludePrivate){
if($isPriv -eq $false){
Write-Output "$o1.$o2.$o3.$o4"
$Count = $Count - 1
}
}
if($ExcludePublic){
if($isPriv -eq $true){
Write-Output "$o1.$o2.$o3.$o4"
$Count = $Count - 1
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment