Generate a random IP address
Return a random IPv4 address from the ranges reserved for documentation.
function randomDocumentationIp() {
const networks = ['192.0.2', '198.51.100', '203.0.113'];
return `${networks[Math.floor(Math.random() * networks.length)]}.${Math.floor(Math.random() * 254) + 1}`;
}
Usage
const ip = randomDocumentationIp();
['192.0.2', '198.51.100', '203.0.113'].includes(ip.split('.').slice(0, 3).join('.')); // → true
randomDocumentationIp(); // e.g. '203.0.113.42'
Know the limits
- RFC 5737 reserves 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24 for documentation. They never belong to a real host, so fixtures and logs in examples cannot point at one.
- The original drew any address: Math.floor(Math.random() * 255) never produced 255, and results included private, loopback and multicast ranges.
- For IPv6 examples, RFC 3849 reserves 2001:db8::/32.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Generate a random IP address from the original 1loc collection by Nguyen Huu Phuoc, with PiyushSuthar, Comet32. Copyright (c) 2020 phuoc-ng. MIT licensed.
Draws from the RFC 5737 documentation ranges; the original never produced 255 and could return private, loopback or multicast addresses. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Generate a random boolean — Return true or false with equal probability.
- Generate a random floating point number in given range — Scale Math.random into [min, max).
- Generate a random hex color — Return a #rrggbb color from 24 random bits.