1
$ nmap -n -iR 0 -sL > RANDOM-IPS-TMP.txt
$ grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" RANDOM-IPS-TMP.txt |
      egrep -v "10.*|172.[16-32].*|192.168.*|[224-255].*" > RANDOM-IPS.txt
egrep: Invalid range end
$ 

How can I generate random IP Addresses outside the private IP address range and the multicast IP Address range?

2
  • 1
    I am afraid to ask why someone wants to generate random ips that feed into nmap. Jun 9, 2011 at 17:47
  • 1
    @Mike: Actually nmap is being used to generate those random IP's, not the other way around. But I too am afraid to ask what they are getting fed INTO! Maybe it's a grand hunt for https only servers?
    – Caleb
    Jun 9, 2011 at 23:34

2 Answers 2

9

You misunderstand regex syntax. [16-32] does not mean "match 16, 17, ... or 32". It means "match one character which is either 1 or 2 or in the range 6-3" (which is not a valid range, hence the error).

It's possible to write a regex to match a range of integers, but it's complex and error prone. In your case, it would be much easier to use nmap's --exclude option to exclude the ranges you don't want. It understands CIDR notation, which is a much simpler way to describe the ranges you're talking about.

nmap -n -iR 0 --exclude 10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,224-255.-.-.- -sL >RANDOM-IPS.txt

You didn't mention the loopback block (127.0.0.0/8), but you probably ought to exclude that too.

1
  • Note to everyone that it's really important to leave the -sL and -n options in place on this, otherwise you're going to scan the internet and may get in trouble for doing so.
    – deltaray
    Apr 20 at 20:29
1

This shell snippet generates an IP address.

ip_address=$(dd if=/dev/urandom bs=4 count=1 2>/dev/null |
             od -An -tu1 |
             sed -e 's/^ *//' -e 's/  */./g')

If you're not happy with it, try again in a loop.

while
  set $(dd if=/dev/urandom bs=4 count=1 2>/dev/null | od -An -tu1)
  [ $1 -lt 224 ] &&
  [ $1 -ne 10 ] &&
  { [ $1 -ne 192 ] || [ $2 -ne 168 ]; } &&
  { [ $1 -ne 172 ] || [ $2 -lt 16 ] || [ $2 -gt 31 ]; }
do :; done
ip_address=$1.$2.$3.$4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.