With split tunnelling, only traffic for listed networks goes through the VPN; everything else goes straight to the internet.
What to build
Decide, for each destination, whether it goes through the tunnel.
Requirements
- Line 1: the tunnelled CIDR blocks, separated by spaces.
- Each following line: a destination IPv4 address.
- Print
ADDRESS tunnel BLOCKwith the first listed block that contains it, orADDRESS direct.
Input
As described.
Output
One line per destination.
Constraints
1 to 10 blocks and up to 50 addresses, all valid.
Example
Input:
10.0.0.0/8 172.16.0.0/12
10.20.1.5
142.250.183.14
172.32.0.1
Output:
10.20.1.5 tunnel 10.0.0.0/8
142.250.183.14 direct
172.32.0.1 direct
Why it works
An address is in a /n block when its first n bits equal the block's, which integer division by 2^(32 − n) tests directly.
Examples
Example 1 · Input
10.0.0.0/8 172.16.0.0/12 10.20.1.5 142.250.183.14 172.32.0.1
Expected output
10.20.1.5 tunnel 10.0.0.0/8 142.250.183.14 direct 172.32.0.1 direct
Example 2 · Input
192.168.1.0/24 192.168.1.255 192.168.2.0
Expected output
192.168.1.255 tunnel 192.168.1.0/24 192.168.2.0 direct
Hints
Hint 1
Turn each address into one number with ((a × 256 + b) × 256 + c) × 256 + d.
Hint 2
Remember /0 contains every address.
Solution
Show one correct solution (try it yourself first)
function toNumber(ip) {
const p = ip.split(".").map(Number);
return ((p[0] * 256 + p[1]) * 256 + p[2]) * 256 + p[3];
}
function inBlock(ip, block) {
if (block === "any") return true;
const [base, bits] = block.split("/");
const size = 2 ** (32 - Number(bits));
return Math.floor(toNumber(ip) / size) === Math.floor(toNumber(base) / size);
}
const blocks = prompt().trim().split(/\s+/);
let line = prompt();
while (line !== null) {
const ip = line.trim();
if (ip) {
const hit = blocks.find((b) => inBlock(ip, b));
console.log(hit ? `${ip} tunnel ${hit}` : `${ip} direct`);
}
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step