Go's net.ParseCIDR in TypeScript

✓ Verified: Go 1.23
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { ParseCIDR } from 'locutus/golang/net/ParseCIDR'.

Or with CommonJS: const { ParseCIDR } = require('locutus/golang/net/ParseCIDR')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1ParseCIDR('192.168.0.1/24'){ip: '192.168.0.1', maskBits: 24}
2ParseCIDR('2001:db8::1/64'){ip: '2001:db8::1', maskBits: 64}
3ParseCIDR('192.168.0.1/99')null

Notes

  • Parses CIDR notation and returns normalized IP plus prefix length.

  • Returns null when either the IP or mask width is invalid.

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to Go's net.ParseCIDR looks like.

import { ParseIP } from './ParseIP.ts'

export type ParsedCIDR = {
ip: string
maskBits: number
}

export function ParseCIDR(value: string): ParsedCIDR | null {
// discuss at: https://locutus.io/golang/net/ParseCIDR/
// parity verified: Go 1.23
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Parses CIDR notation and returns normalized IP plus prefix length.
// note 2: Returns null when either the IP or mask width is invalid.
// example 1: ParseCIDR('192.168.0.1/24')
// returns 1: {ip: '192.168.0.1', maskBits: 24}
// example 2: ParseCIDR('2001:db8::1/64')
// returns 2: {ip: '2001:db8::1', maskBits: 64}
// example 3: ParseCIDR('192.168.0.1/99')
// returns 3: null

const input = String(value)
const slashIndex = input.indexOf('/')
if (slashIndex <= 0 || slashIndex !== input.lastIndexOf('/')) {
return null
}

const ipPart = input.slice(0, slashIndex)
const maskPart = input.slice(slashIndex + 1)
if (!/^\d+$/.test(maskPart)) {
return null
}

const normalizedIp = ParseIP(ipPart)
if (normalizedIp === null) {
return null
}

const maxBits = normalizedIp.includes(':') ? 128 : 32
const maskBits = Number(maskPart)
if (!Number.isInteger(maskBits) || maskBits < 0 || maskBits > maxBits) {
return null
}

return {
ip: normalizedIp,
maskBits,
}
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


Help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Go net functions


Star