Random IP for testing

twitter logo github logo Updated on ・1 min read

Sometimes you need to create valid IP addresses, which can be used without interfering running infrastructure.
The easiest thing is to take a address which is tied to localhost, so traffic
never leaves your dev machine or environment.
Every address from 127.0.0.1 up to 127.255.255.254 does so.

For IP version 4 this could be done like this:

import random
# should be called once
random.seed()

def getLocalv4Addr():
    return [127,random.randint(0,255),random.randint(0,255),random.randint(1,254)]

With IP version 6 there is only one loopback address, ::1.
So in that case you need to setup something else, e.g. you could
run your tests inside a docker container and do not expose any network to the outside.

twitter logo DISCUSS (6)
markdown guide
 

Yes, this does work. If that's all you need, that's great. Stop reading here. You're happy, you've got a shedload of new IPs to use.

But if you want to understand what is happening, it doesn't "resolve to localhost" unless your DNS or /etc/hosts says it does (which is unlikely). This technique doesn't rely on name resolution at all. What does happen is that your loopback device responds to that IP address. It responds to every address on the 127.x.x.x (aka 127/8) network.

On a typical Linux box, run "ip a" and it shows the "lo" device as "inet 127.0.0.1/8". That "/8" means "only the first 8 bits (the first byte, the "127") are the network part; the other 24 bits (in an IPv4 address) are host addresses. So it's a big network, known as a "Class A" subnet.
The loopback device is a device driver which responds to all addresses on its subnet.
So that is how this works; the device driver controlling the loopback address responds to your packet.

 

Fair enough to say that the term resolving is misleading.
As you pointed out, there is no name resolution in any way involved.
I updated the post to reflect this.

 

So simple, why did not I think about it before? i always use an array of manually defined values

Is there a "faker" for python?

 
 

Something like this exists.

But I don't get the point of this. I usually create completely random test data which only has to conform to some form of semantic or syntactic specification.
It doesn't need to be human-readable, as systems tend to be not humans ;-)

Classic DEV Post from Sep 13 '18

Have any DEV design concepts or ideas?

pythonmeister profile image
Senior DevOps with emphasis on Ops.

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️