IP Block Subtraction Calculator
A tool to subtract a set of IP blocks from another.
I've been messing around with Wireguard recently. Wireguard is a VPN with a pretty simple configuration. One of the most important options is AllowedIPs
, which determines the IP addresses that will be routed through the VPN. This is written in CIDR notation. For example, if you want to route all internet traffic through the VPN, you would put in AllowedIPs = 0.0.0.0/0
.
However, there's no simple way to exclude certain IP blocks from this setting. You need to calculate the IP blocks manually before putting them in the configuration. And because of how CIDR notation works, it's pretty difficult to calculate manually.
I found an online calculator that can compute this, which works quite well. However, this seems like an interesting puzzle, so I wanted to make my own. I also wanted to make something with PureScript for a while, so I used it for the calculation logic (though I still used Svelte for the UI).
I used the Either type in the parsing logic, which makes it very easy to propagate the parsing error messages to the caller. I also wrote some of the logic in a recursive way, which can be done very naturally in PureScript.
The one thing I found annoying is the number literal handling. I needed to use a BigInt
type to avoid some bitwise operation issues when the IP address uses the 32nd bit, but writing a number like 1
will always create a primitive integer. And because of its strong typing, I can't just write someBigInt + 1
, I needed to write someBigInt + (fromInt 1)
instead (where fromInt
converts a primitive integer to a BigInt
).
In the end, I defined a bunch of constants for commonly used numbers (b1 = fromInt 1
, b2 = fromInt 2
, etc). I'm not sure if there's a better way to do this. If you know of one, please let me know in the comments!
You can check out the UI code here, and the calculation code here.