Skip to main content

Counting to Four Billion

Scanning the whole internet in random order with no list, no bitmap and no coordination, using math older than the internet. Every address exactly once, distributed across as many machines as you want, using linear congruential generators, Feistel networks, and more.

Updated 24 min readMarkdown
Counting to Four Billion

Most of the math taught in school never gets a reason to exist. You are not in a job or a place in life where any of it applies to you, so it turns into a list of formulas you are told are important, you memorize them for the test, and then a calculator does the rest for the next 20 fucking years. Very few people walk out of algebra still thinking about remainders.

I didn't care about math until I started writing code and scanning the internet. At that scale, throwing more servers at a problem doesn't always fix it, but a couple of lines of math from the 1960s does. Watching something that small solve something that big is what got me hooked.

Take scanning every IPv4 address. How do you hit all 4.29 billion of them in a random order, without ever repeating one or skipping one, and without keeping track of what you already did? What if you want to split that across 10 or 100 machines that never talk to each other? While digging into that, and getting a little obsessed with the math behind it, I wrote a tool called clcg. This post walks through how it works, and how nerdy I got with understanding the math and optimizing it for speed, since there's no standard library out there that just does this. Hopefully it gets you appreciating math a little more too.

Addresses Are Numbers

The dotted format of an IPv4 address is only for people. Underneath it is a 32-bit unsigned integer, four bytes, one per octet:

192.168.1.1 as four octets, their bits, and the 32-bit integer 3,232,235,777

Each octet is one byte. Shifted into its own 8-bit slot, (192 << 24) | (168 << 16) | (1 << 8) | 1, the four bytes make one 32-bit number. Shifting left by 8 is the same as multiplying by 256, so each octet is worth 256 times the one to its right.

32 bits gives 2³² = 4,294,967,296 values, from 0.0.0.0 to 255.255.255.255. Scanning the internet comes down to counting from 0 to 4,294,967,295 and sending a packet for each number. What matters is the order you count in.

Counting in Order

The obvious loop is 0, 1, 2, 3. Addresses are handed out in contiguous blocks, so counting in order walks straight through one organization's range, address after address, before it ever touches the next one:

Addresses counting up from 1.0.0.0, filling one /24 network completely before moving to the next

A /16, a university or an ISP region, gets all 65,536 of its probes back to back with nothing else in between. That trips every IDS and rate limit they have, an abuse report lands with your provider, and once they start dropping you, the rest of their range is missing from your results without any sign that it is. To anyone watching their logs, it's a very obvious sign that someone is crawling all over their infrastructure.

Splitting Into Blocks

The next idea is to break the space into blocks and randomize the blocks. Give each machine its own /8, or shuffle the list of /16s or /24s and sweep them in random order. This moves the burst around without getting rid of it. Inside each block you are still counting in order, so every /16 still receives its 65,536 probes back to back, and every /24 its 256. Shuffling /24s is the best case for this approach, and every network still sees its whole range probed in one burst.

Eight /24 networks visited in a shuffled order, each one swept from .0 to .255 in a single burst

Spreading the load means consecutive probes have nothing to do with each other, so the shuffle has to happen at the level of single addresses.

Keeping Track of Every Address

There are two direct ways to do that, and both run out of memory or time.

Shuffle a list up front. A packed array of 2³² uint32 values is 17,179,869,184 bytes, 16 GiB, before the first packet goes out. Every machine in a cluster also needs the identical shuffled list, or some way to agree on who owns which part of it.

Pick random addresses and remember which ones are done. The cost depends on where you keep the record.

  • In a list. Checking whether an address is already in an unsorted list means comparing it against every entry until you find a match or reach the end. A list of every address is the same 16 GiB, and since each new address gets checked against everything before it, a full run adds up to about 9.2 x 10¹⁸ comparisons.
  • In a hash set. Lookups become constant time, but a hash table stores every address plus the empty slots and bookkeeping that keep those lookups fast, so it costs well over the 16 GiB the addresses take on their own.
  • In a file. Append each scanned address as a line of text. Across the whole space the average line is 14.28 bytes, so the finished file is 61,337,501,696 bytes, about 57 GiB. Appending is cheap. Checking whether an address is already in the file means reading the file, and the file keeps growing, so every check takes longer than the last. Summed over the run, the checks read 1.3 x 10²⁰ bytes.
  • In a bitmap. One bit per address is 2³² bits, 512 MiB, with constant-time lookups. Even so, random picks do not finish. Send 4.29 billion random probes, one per address, and you will only have covered about 63.2% of the internet. The other 36.8% of your probes hit addresses you already had. The reason is that the chance of a new address keeps shrinking: it equals the fraction you have not seen yet, so the last few addresses take forever to land on. Statisticians call this the coupon collector's problem. Seeing every one of n values takes about n x (ln(n) + 0.5772) picks, which for the IPv4 space is 22.76 times its size, around 97.7 billion probes. The bitmap also has to be shared between every machine, which is the coordination I was trying to avoid.
Probe order over 1,024 addresses: sequential, shuffled blocks, random picks with tracking that cover only 663 of 1,024 after 1,024 picks, and clcg

Remainders

So the requirements are: every address exactly once, no record of what has already been done, and a way to divide the work between machines that never talk to each other. The order cannot be stored anywhere. It has to be computed.

The tool for this is modular arithmetic. The modulo operation, written mod, gives you the remainder after dividing one number by another: 17 mod 5 = 2, because 5 goes into 17 three times with 2 left over. It works like a clock: 10 o'clock plus 5 hours is 3 o'clock, because 12 goes into 15 once with 3 left over, so 15 mod 12 = 3. However large a number gets, x mod m always lands between 0 and m - 1.

12 hour clock: 10 plus 5 wraps around to 3

Powers of two make this especially cheap. In decimal, the remainder after dividing by 1,000 is just the last three digits: 123,456 mod 1,000 = 456. Binary works the same way, so the remainder after dividing by 16, which is 2⁴, is just the last four bits:

67         =  100 0011
67 mod 16  =      0011  =  3

No division needed, the computer just drops the higher bits. With m = 2³² it does not even have to do that. A 32-bit number works like a car odometer with 32 binary digits: when it passes its maximum it rolls back over to zero and keeps counting. Every add and multiply that overflows wraps around on its own, so the IPv4 space is a clock with 2³² positions that the CPU wraps around for free, with no extra instructions.

Linear Congruential Generators

Xₙ₊₁ = (a x Xₙ + c) mod m

Multiply the current value by a, add c, wrap modulo m, and that is the next value. This is a linear congruential generator. D. H. Lehmer described the multiplicative form in 1949, and for decades it was the default random number generator in many standard libraries. Java's still is. Run it on a clock with 16 positions, a = 5, c = 3, starting from 0:

An LCG with a = 5, c = 3, m = 16 visiting every position on a 16 position clock

Every value from 0 to 15 appears exactly once, in a scattered order: 3, 2, 13, 4, 7, 6, 1, 8, 11, 10, 5, 12, 15, 14, 9, 0. The 17th step lands back on 3. The only thing carried from one step to the next is the current value, so the full state of the walk is a single integer, no matter how many addresses have already been visited.

Choosing a and c

Most values of a and c do not give a full cycle. On the same 16 position clock, starting from 0:

Four LCGs on a 16 position clock, only a = 5, c = 3 visits every position

The bad ones fall into a short loop and never reach the rest of the clock. As a scanner, that misses half the internet or nearly all of it, and the output still looks random enough that nothing seems wrong.

Hull and Dobell proved in 1962 exactly which values work. An LCG has a full period, visiting every value modulo m once, if and only if:

  1. c and m share no common factor.
  2. a - 1 is divisible by every prime factor of m.
  3. a - 1 is divisible by 4 if m is.

When m is a power of two its only prime factor is 2, and the three conditions reduce to two: c is odd, and a - 1 is divisible by 4. Of the four clocks, a = 5, c = 3 passes both. c = 2 is even. a = 3 gives a - 1 = 2, and a = 4 gives 3, neither divisible by 4.

I went with a = 1,664,525, the multiplier from Numerical Recipes. 1,664,524 = 4 x 416,131, so the second condition holds for every power of two. I did not want c to be a fixed constant, so it is derived from the seed with splitmix64 and its lowest bit is forced to 1, so it is always odd and the full period is guaranteed for any modulus 2ᵏ, IPv4 or IPv6. A different c also means a different successor for every value, since a x v + c changes with c, so two seeds give two different orders instead of the same cycle started at two different points.

Indexes and Addresses

The generator produces indexes, not addresses. Number the target addresses that are left after exclusions from 0 to N - 1, set the clock to 2ᵏ, the smallest power of two at or above N, and skip any index of N or more. Since 2ᵏ < 2N, fewer than half of the steps are ever skipped, and a plain CIDR skips none. Excluding private and reserved space from 0.0.0.0/0:

0.0.0.0/0                   4,294,967,296
private & reserved        -   592,708,864
──────────────────────────────────────────
N                           3,702,258,432
skipped steps                       13.8%

Excluded addresses are never generated and then thrown away. They are not part of the index space at all. A sorted table of the exclusions maps index i to the ith address that is not excluded, so 10.0.0.0/8 never comes up, and the only waste is the 13.8% of steps past N, each costing one generator step and one mix.

Jumping Ahead

One step is x -> 5x + 3. Two steps is that function applied to itself:

one step:   x  ->  5x + 3
two steps:  x  ->  5(5x + 3) + 3  =  25x + 18  =  9x + 2   (mod 16)

Two steps of an LCG is another single-step LCG with different constants. From 3, two steps should land on 13, and 9 x 3 + 2 = 29, 29 mod 16 = 13. In general, applying (a₁, c₁) and then (a₂, c₂) gives:

(a₂ x a₁,  a₂ x c₁ + c₂)

Compose the 2-step constants with themselves for 4 steps, then 8, 16, 32. Any step count is a sum of those powers of two, the same way any number is written in binary, so a jump of n steps takes one squaring per bit of n and one composition per set bit. This is exponentiation by squaring, the same trick used for modular exponentiation in RSA. In C:

/* Compose n steps of x -> a*x + c into one (a, c), modulo the power of 2 behind mask */
static void jump_params(u128 n, u128 c, u128 mask, u128 *ra, u128 *rc) {
        u128 a = 1, b = 0, sa = LCG_A & mask, sc = c & mask;

        while (n) {
                if (n & 1) {
                        a = (sa * a) & mask;
                        b = (sa * b + sc) & mask;
                }

                sc = (sa * sc + sc) & mask;
                sa = (sa * sa) & mask;
                n >>= 1;
        }

        *ra = a;
        *rc = b;
}

It works in 128-bit arithmetic so the same code covers IPv6. Jumping 10⁹ steps from 0 lands on 2,621,190,656, the same value walking those 10⁹ steps one at a time produces. The loop runs once per bit of the step count, so any jump in the IPv4 space takes at most 32 passes instead of up to 4,294,967,295 steps.

Sharding and Resuming

The cycle contains every index exactly once, so it can be dealt out like a deck of cards. Shard i of T takes steps i, i + T, i + 2T, and so on. On the 16 position clock with 4 machines:

The 16 step cycle dealt across 4 machines, each machine landing on one remainder mod 4

Every value lands in exactly one row, and every machine gets an equal share. Each one only needs the seed, the shard count, and its own shard number. No central server hands out work and nothing is shared between machines while they run.

Jumping is what makes this cheap. At startup a shard jumps straight to its first step, then computes the T-step constants once and uses them for every step after that. It never computes another shard's indexes, so the work per machine drops as 1/T. Resuming works the same way.

Since the seed fixes the entire order, where a scan is comes down to one number: how many steps it has taken. If a scan dies 1.83 billion steps in, saving the seed, the target range, the shard layout and that step count is enough to jump straight back to step 1,830,000,000 and keep going. I also save a hash of the exclusion list, so resuming with a different blocklist gets refused instead of quietly walking a different order.

The Low Bits Repeat

The squares in the sharding figure show a problem. Machine 1 got 3, 7, 11 and 15, all of them 3 mod 4. Machine 2 got 2, 6, 10, 14. Each machine is stuck on a single remainder.

Write the 16 position sequence in binary and look at each row of bits:

Bits of the LCG output, each bit repeating with period 2, 4, 8 and 16

The reason is in the formula. The bottom j bits of a x X + c depend only on the bottom j bits of X, so the bottom j bits of a power-of-two LCG are an LCG of their own modulo 2ʲ, and they cycle with period 2ʲ. The lowest bit flips on every step. The last octet runs through all 256 values every 256 steps.

On the real 2³² cycle the pattern is there in the first few outputs. These are the first outputs for seed 1337, with the mixer described below turned off:

236.123.255.174
201.255.85.159
194.113.184.220
164.192.16.245
244.69.128.58
6.30.164.187

Even, odd, even, odd, even, odd. For scanning that is more than cosmetic. With 2 shards, one shard only ever probes even addresses and the other only odd ones. With 256 shards, every shard probes a single last octet for the whole run, so one machine sends nothing but probes to .0 addresses and another nothing but .255. I ran the full 2³² cycle and checked:

Raw LCG, full 2^32 cycle, seed 1337
──────────────────────────────────────────────────────
Consecutive addresses with the same parity     0%
2 shards, even addresses in shard 1 / 2        100% / 0%
256 shards, last octet within each shard       constant

LCGs are never used for cryptography for the same reason: a few outputs give away the rest of the sequence. A scanner does not need to be unpredictable to an attacker, but it does need the order to have no structure a network or a shard layout can line up with.

Mixing the Output

The fix I went with keeps the LCG as a counter and passes each value through a mixer before using it as an index:

static inline uint64_t mix64(uint64_t x, unsigned s, uint64_t mask) {
        x ^= x >> s; x = (x * MIX_M1) & mask;
        x ^= x >> s; x = (x * MIX_M2) & mask;
        x ^= x >> s;
        return x;
}

Here mask is 2ᵏ - 1 and s is k/2 rounded up. The multiplies carry low bits up into the high bits, and the shifts fold high bits back down into the low ones. The mixer is still a permutation of 0 .. 2ᵏ - 1, because every operation in it can be undone:

  • Multiplying by an odd number modulo 2ᵏ is invertible, since an odd number shares no factor with 2ᵏ.
  • x ^= x >> s undoes itself. Applying it twice gives x ^ (x >> 2s), and x >> 2s = 0 because 2s >= k.
Two inputs one bit apart passing through the mixer, ending 5 bits apart

An 8-bit version of the mixer (s = 4, multipliers taken mod 256) on two inputs that differ only in the lowest bit. White marks the bits that differ. The multiplies carry the difference upward, the shifts fold it back down, and these two outputs end up 5 bits apart. Over every such pair the 8-bit version averages 4.3 of 8. At the real 32-bit size it averages 16.0 of 32, exactly half, which is what an ideal mix gives.

Bits of the mixed output with no repeating columns

The same 16 steps after the mixer, shrunk to 4 bits (s = 2, multipliers taken mod 16). Still all 16 values exactly once, and the bottom bit no longer alternates.

A chain of invertible steps is invertible, so the mixed sequence still visits every index exactly once, and sharding and jumping are untouched because they act on the counter, not the output. The constants are 0x9E3779B97F4A7C15, which is 2⁶⁴ divided by the golden ratio, and 0xBF58476D1CE4E5B9 from splitmix64. Only their being odd matters for correctness. The same full cycle with the mixer on:

Full 2^32 cycle, seed 1337            Raw LCG       Mixed
───────────────────────────────────────────────────────────
Every address exactly once            yes           yes
Consecutive same parity               0%            49.9995%
2 shards, even in shard 1 / 2         100% / 0%     50% / 50%
256 shards, last octet per shard      constant      varies
Shortest gap to 8.8.8.0/24            28,278        28,699
Longest gap to 8.8.8.0/24             74,639,108    87,506,599
/24s hit twice back to back           272           236

The gap rows barely move, and they should not. Each /24 is hit once every 2²⁴ = 16,777,216 steps on average either way, and a truly random order would put about 255 back-to-back pairs inside the same /24 somewhere among all 16.7 million of them. Both versions sit near that. The raw LCG was never bad at spreading probes across networks. Its problem was which addresses come out together, and which shard ends up with them.

To be sure, I ran the whole of 0.0.0.0/0 through it, with and without exclusions and across shards, marking each address in a 512 MiB bitmap. Split 3 ways with seed 12345 it produced 4,294,967,296 distinct addresses with no duplicates, and with private space excluded, 3,702,258,432 with no excluded address leaking through.

The mixer costs about a quarter of a nanosecond per index: 1.2 ns for a bare LCG step, 1.45 ns with the mixer.

IP and Port Pairs

I also wanted to shuffle every IP:port pair instead of every IP. For N addresses and P ports, pair t is address index t mod N on port slot t / N, and the domain is the smallest power of two at or above N x P. For pairs I swapped the LCG and the mixer for a different kind of permutation, a Feistel network.

Feistel Networks

A Feistel network builds a permutation out of a function that is not one. Horst Feistel designed it at IBM in the early 1970s for the Lucifer cipher, and it became the structure of DES, which is 16 rounds of it. The mixer above only works because every step in it was picked to be reversible. A Feistel network drops that requirement. The function inside it can collide, throw information away, or be anything at all, and the whole thing is still a permutation.

Split the input bits into a left half L and a right half R. One round, with a function F and a round key k:

L' = R
R' = L xor F(R, k)
Two rounds of a Feistel network

Running a round backwards needs nothing but its output. L' is the old R, so R is already there. With R known, F(R, k) can be computed again, and since XOR undoes itself, (L xor F(R, k)) xor F(R, k) = L:

R = L'
L = R' xor F(L', k)

F is only ever computed forwards, never inverted. To show that it really can be anything, here is a 4-bit domain with 2-bit halves and a deliberately bad function, F(r, k) = (r x r + k) mod 4. A square mod 4 is always 0 or 1, so F sends its four possible inputs to only two outputs and loses half of what it is given. Three rounds with keys 1, 2 and 3 on the input 6:

Three Feistel rounds taking 6 to 3, and the same rounds undone taking 3 back to 6

Every one of the 16 inputs goes through the same three rounds and comes out as a different value:

F maps 4 inputs onto 2 outputs, yet 3 Feistel rounds using it map 16 inputs onto 16 distinct outputs

Left: F on its own collides, 0 and 2 both give 1, 1 and 3 both give 2. Right: the three rounds built from it send every 4-bit input to a different output, so the network is a permutation even though F is not.

The number of rounds decides how well it scrambles, not whether it is a permutation. After one round the new L is a straight copy of the old R, so half the output is just input moved over. After two rounds the output's high half is L xor F(R), so flipping a bit of L still flips exactly one output bit and nothing else. Every input bit has to pass through F a few times before every output bit depends on it.

The F I use is a splitmix64 finalizer, two multiplies and three XORs, with one key per round derived from the seed. The two halves can differ by one bit and trade sizes each round, so any power of two works, and values past N x P are skipped the same way as before. The input to the network is just the step position, i - 1, i - 1 + T, and so on. Any position can be fed in directly, so sharding and resuming need no jump at all.

The number of rounds is the tradeoff. A good permutation flips each output bit with probability 1/2 when any one input bit flips. I measured that on a 32-bit domain over 200,000 random inputs, where the noise floor for the worst of the 1,024 input/output bit pairs is about 0.0045:

Rounds   Avg output bits flipped   Worst bit bias
──────────────────────────────────────────────────
1         5.00 / 32                 0.5000
2        12.50 / 32                 0.5000
3        16.00 / 32                 0.0091
4        16.00 / 32                 0.0034
8        16.00 / 32                 0.0045

One and two rounds show a bias of 0.5, the copied and directly flipped bits described above. Four rounds are indistinguishable from noise, which is why I settled on 4.

ZMap and masscan

The two well known internet scanners solve the same problem differently. ZMap walks the multiplicative group of integers modulo p = 2³² + 15, the smallest prime above 2³². Repeatedly multiplying by a primitive root visits every value from 1 to p - 1 once, and the handful above 2³² are skipped. Every step is a multiply followed by a remainder by that prime, which takes real arithmetic, where clcg's power-of-two remainder costs nothing. masscan uses BlackRock, a Feistel-based cipher over an arbitrary domain following Black and Rogaway, with 14 rounds by default. Built from masscan's source and timed side by side, BlackRock took about 200 ns per index at 14 rounds and 55 ns at 4, against 1.45 ns for clcg, roughly 140 times faster than masscan's default. Both of those generators also live inside their scanners, while clcg is a standalone library that any tool can pull addresses from.

clcg turns out about 137 million addresses per second as text on a single core, so the generator is never what slows a scan down.

Wrapping Around

None of this is advanced math. Remainders, binary, divisibility by four, plugging a function into itself. It is the same stuff that felt pointless on a worksheet, and it turned out to be the cleanest way I have found to walk the entire internet.

It is not just scanning either. The large language models people treat as the most advanced technology around come down to the same kind of material. Under the hood they are mostly matrix multiplication, multiplying and adding grids of numbers, the kind of thing taught in a high school or first year college class, repeated billions of times over. The scale is what is impressive. The math underneath is stuff most of us were taught and forgot.

That is what changed math for me. Not that it got easier, but that it finally had a job. If you want to see all of this in actual code, it lives in clcg.

Sources & References:

About the author

No comments yet. Be the first to comment.