IPv4/IPv6 CIDR notation parsing and operations for Nim. Zero dependencies — builds on std/net's IpAddress.
import cidr, std/net
let net = parseCidr("192.168.1.0/24")
echo net.contains(parseIpAddress("192.168.1.55")) # true
echo parseIpAddress("192.168.2.1") in net # false
echo net.lastAddress # 192.168.1.255
echo parseCidr("10.1.2.3/8").normalized # 10.0.0.0/8
echo toPrefixLen(parseIpAddress("255.255.255.0")) # 24std/net gives you IpAddress, but nothing for working with networks: no CIDR parsing, no containment checks, no overlap detection. Every firewall tool, log analyzer, IP allowlist and server dashboard ends up reinventing that. cidr fills the gap with a small, well-tested API.
-
Parse IPv4 and IPv6 CIDR blocks (
10.0.0.0/8,2001:db8::/32), bare addresses become host blocks (/32,/128) -
Containment:
net.contains(ip)andbigNet.contains(smallNet) - Overlap detection between blocks
- Network / last address (broadcast/top), host-bit normalization
-
Netmask conversion:
255.255.255.0→/24(rejects non-contiguous masks) -
Block size (
/24→ 256 addresses), saturating for huge IPv6 blocks - Zero dependencies, pure standard library,
CidrError(aValueError) on bad input
nimble install cidr
or add to your .nimble:
requires "cidr >= 0.1.0"
| Proc | Description |
|---|---|
parseCidr(s: string): Cidr |
Parse a.b.c.d/len, host bits normalized |
c.contains(ip: IpAddress): bool |
Address membership (in works too) |
outer.contains(inner: Cidr): bool |
Subnet containment |
overlaps(a, b: Cidr): bool |
Do the blocks share any address? |
c.networkAddress / c.lastAddress |
First / top address of the block |
c.normalized |
Canonical form with host bits cleared |
c.size: BiggestUInt |
Number of addresses (saturates at 2^64) |
toPrefixLen(netmask: IpAddress): int |
Netmask → prefix length |
import cidr, std/net
const PrivateNets = [parseCidr("10.0.0.0/8"), parseCidr("172.16.0.0/12"),
parseCidr("192.168.0.0/16")]
proc isPrivate(ip: IpAddress): bool =
PrivateNets.anyIt(it.contains(ip))
echo isPrivate(parseIpAddress("192.168.0.1")) # true
echo isPrivate(parseIpAddress("8.8.8.8")) # falsenimble test
21 unit tests, CI on Nim 1.6 / 2.0 / stable.
MIT