Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
$ 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?

share|improve this question
I am afraid to ask why someone wants to generate random ips that feed into nmap. – Mike Pennington Jun 9 '11 at 17:47
@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 '11 at 23:34
up vote 5 down vote accepted

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,,,224-255.-.-.- -sL >RANDOM-IPS.txt

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

share|improve this answer

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.

  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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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