{"id":11096,"library":"ipaddr.js","title":"ipaddr.js","description":"ipaddr.js is a lightweight JavaScript library (1.9K minified+gzipped) designed for comprehensive manipulation of both IPv4 and IPv6 addresses. Its current stable version is 2.3.0, and it maintains a steady release cadence for bug fixes and minor improvements. The library functions effectively in both CommonJS (Node.js 10+) and browser environments, shipping with TypeScript types for enhanced development. Key functionalities include validating and parsing IP address strings, matching addresses against CIDR ranges or custom range lists, identifying reserved IP address ranges (e.g., loopback, private), and automatically converting IPv4-mapped IPv6 addresses to their IPv4 equivalents, which is particularly useful for Node.js servers listening on IPv6 sockets. Its primary differentiator is its small footprint and comprehensive set of core IP address utilities without external dependencies.","status":"active","version":"2.3.0","language":"javascript","source_language":"en","source_url":"git://github.com/whitequark/ipaddr.js","tags":["javascript","ip","ipv4","ipv6","typescript"],"install":[{"cmd":"npm install ipaddr.js","lang":"bash","label":"npm"},{"cmd":"yarn add ipaddr.js","lang":"bash","label":"yarn"},{"cmd":"pnpm add ipaddr.js","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library exports a default object named `ipaddr` containing all methods and classes.","wrong":"import { ipaddr } from 'ipaddr.js';","symbol":"ipaddr","correct":"import ipaddr from 'ipaddr.js';"},{"note":"Standard CommonJS import pattern, compatible with older Node.js environments and bundlers.","symbol":"ipaddr (CommonJS)","correct":"const ipaddr = require('ipaddr.js');"},{"note":"These are TypeScript type definitions, not runtime values. Use `import type` to avoid bundling issues.","wrong":"import { IPv4, IPv6 } from 'ipaddr.js';","symbol":"IPv4, IPv6 (Types)","correct":"import type { IPv4, IPv6, Address, Subnet } from 'ipaddr.js';"}],"quickstart":{"code":"import ipaddr from 'ipaddr.js';\n\n// --- Validation and Parsing --- \n\nconst ipAddressStringV4 = '192.168.1.100';\nconst ipAddressStringV6 = '2001:0db8:85a3::8a2e:0370:7334';\nconst invalidIp = '999.999.999.999';\nconst cidrV4 = '192.168.1.0/24';\nconst cidrV6 = '2001:db8::/32';\n\nconsole.log(`Is '${ipAddressStringV4}' valid? ${ipaddr.isValid(ipAddressStringV4)}`);\nconsole.log(`Is '${invalidIp}' valid? ${ipaddr.isValid(invalidIp)}`);\n\ntry {\n  const parsedV4 = ipaddr.parse(ipAddressStringV4);\n  console.log(`Parsed IPv4: ${parsedV4.toString()} (Kind: ${parsedV4.kind()})`);\n\n  const parsedV6 = ipaddr.parse(ipAddressStringV6);\n  console.log(`Parsed IPv6: ${parsedV6.toString()} (Kind: ${parsedV6.kind()})`);\n\n  // Demonstrate process() with an IPv4-mapped IPv6 address\n  const mappedV4inV6 = '::ffff:192.168.1.100';\n  const processedAddr = ipaddr.process(mappedV4inV6);\n  console.log(`Processed '${mappedV4inV6}': ${processedAddr.toString()} (Kind: ${processedAddr.kind()})`);\n\n  // --- CIDR Matching ---\n  console.log(`Is '${cidrV4}' a valid CIDR? ${ipaddr.isValidCIDR(cidrV4)}`);\n\n  const ipToMatchV4 = ipaddr.parse('192.168.1.50');\n  const [rangeV4, bitsV4] = ipaddr.parseCIDR(cidrV4);\n  console.log(`Does ${ipToMatchV4.toString()} match ${cidrV4}? ${ipToMatchV4.match(rangeV4, bitsV4)}`);\n\n  const ipToMatchV6 = ipaddr.parse('2001:db8:ffff::1');\n  const [rangeV6, bitsV6] = ipaddr.parseCIDR(cidrV6);\n  console.log(`Does ${ipToMatchV6.toString()} match ${cidrV6}? ${ipToMatchV6.match(rangeV6, bitsV6)}`);\n\n  // --- Special Ranges ---\n  const loopbackV4 = ipaddr.parse('127.0.0.1');\n  console.log(`'${loopbackV4.toString()}' is a '${loopbackV4.range()}' address.`);\n\n  const privateV4 = ipaddr.parse('10.0.0.1');\n  console.log(`'${privateV4.toString()}' is a '${privateV4.range()}' address.`);\n\n} catch (error: any) {\n  console.error(`Error parsing IP address: ${error.message}`);\n}\n\n// Example of incorrect usage (type mismatch for match)\ntry {\n    const ipv4 = ipaddr.parse('192.168.1.1');\n    const ipv6Range = ipaddr.parse('2001:db8::');\n    // The .match method expects arguments of the same IP address family.\n    // Attempting this will not work as expected and might throw a runtime error.\n    // console.log(ipv4.match(ipv6Range, 16));\n} catch (e: any) {\n    // This catch block would normally handle a TypeError if the match method was called with mismatched types.\n    // The actual method will silently return false or throw based on its internal logic, highlighting a gotcha.\n    // For demonstration, we'll just acknowledge the mismatch.\n    console.warn(\"Attempted to match IPv4 against IPv6 range. (Expected type mismatch, handled gracefully or via explicit check).\");\n}","lang":"typescript","description":"Demonstrates parsing, validating, processing IPv4 and IPv6 addresses, CIDR matching, and identifying special IP ranges like loopback and private networks. Includes error handling for invalid inputs."},"warnings":[{"fix":"Upgrade Node.js to version 10+ or downgrade `ipaddr.js` to a `1.x` release using `npm install ipaddr.js@^1`.","message":"Version 2.x of `ipaddr.js` requires Node.js version 10 or higher. For applications targeting older Node.js environments (prior to Node.js 10), you must use the `1.x` release series of `ipaddr.js`.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always wrap calls to `ipaddr.parse()` in a `try...catch` block, or pre-validate input using `ipaddr.isValid()` to prevent application crashes from invalid user input.","message":"The `ipaddr.parse()` method throws an `Error` for syntactically invalid IP address strings. In contrast, `ipaddr.isValid()` and `ipaddr.isValidCIDR()` return a boolean `false` without throwing an exception.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Do not rely on `addr.toString()` to perfectly replicate the exact input string. If the original string is needed, it must be stored separately.","message":"The `toString()` method on `IPv4` and `IPv6` objects returns a compact, normalized string representation of the IP address, which may not be identical to the original input string used to create the object. This is by design, as the library normalizes addresses.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Before calling `match()`, ensure both the address and the range are of the same type (IPv4 or IPv6) using `addr.kind()` or `ipaddr.parse().kind()`.","message":"The `addr.match(range, bits)` method can only compare an address against a CIDR range of the *same IP address family*. Attempting to match an IPv4 address against an IPv6 range (or vice-versa) will result in incorrect behavior or potential runtime errors.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Validate the input string with `ipaddr.isValid()` before parsing, or wrap `ipaddr.parse()` calls in a `try...catch` block to handle exceptions gracefully.","cause":"Attempting to parse a malformed or syntactically incorrect IP address string using `ipaddr.parse()` without error handling.","error":"Error: Invalid IP address"},{"fix":"For CommonJS, use `const ipaddr = require('ipaddr.js');`. For ES modules, use `import ipaddr from 'ipaddr.js';`. Do not use named imports like `import { ipaddr } from 'ipaddr.js';`.","cause":"Incorrect CommonJS `require` or ES module `import` syntax, leading to the `ipaddr` variable not correctly referencing the default export object.","error":"TypeError: ipaddr.isValid is not a function"},{"fix":"Ensure `ipaddr.js` is correctly installed. If the issue persists, verify your `tsconfig.json` paths or consider installing `@types/ipaddr.js` as a dev dependency (though typically not needed for recent versions of `ipaddr.js`).","cause":"TypeScript compiler is unable to locate the type definition files for `ipaddr.js`. While `ipaddr.js` ships with its own types, this can occur in certain project configurations or if an older version is in use.","error":"TS2307: Cannot find module 'ipaddr.js' or its corresponding type declarations."}],"ecosystem":"npm"}