ipaddr.js

repository·main·Indexed 20 days ago

https://github.com/whitequark/ipaddr.js

A JavaScript library for manipulating IPv4 and IPv6 addresses, supporting both Node.js and browser environments. Version 2.4.0 provides functionality to validate, parse, and convert IP addresses and CIDR notation. It includes tools for calculating network and broadcast addresses, matching addresses against ranges or named subnet lists, and identifying address range types (such as loopback, private, and multicast). It also supports conversion between IPv4 and IPv4-mapped IPv6 addresses.

Tokens
7.3K
Snippets
32
Records
32
Agent score
69%

What's inside ipaddr.js

  1. Quick start with ipaddr.js

    main

    Import the library and use the global API to validate addresses, parse them into objects, or parse CIDR notation.

    Note: ipaddr.parse() and ipaddr.parseCIDR() will throw an error if the input is invalid. Use ipaddr.isValid() or ipaddr.isValidCIDR() to check validity without throwing.

    const ipaddr = require('ipaddr.js');
    
    ipaddr.isValid('192.168.1.1');     // => true
    ipaddr.isValid('2001:db8::1');    // => true
    ipaddr.isValid('not an address'); // => false
    
    const addr = ipaddr.parse('2001:db8::1');
    addr.kind();     // => 'ipv6'
    addr.toString(); // => '2001:db8::1'
    
    const [network, prefix] = ipaddr.parseCIDR('10.0.0.0/8');
    network.toString(); // => '10.0.0.0'
    prefix;             // => 8
  2. Access IPv4 special ranges

    main

    The IPv4 class provides a SpecialRanges property containing predefined subnets for common address types. You can use these with ipaddr.subnetMatch() to identify the type of an address.

    Available ranges include:

    • unspecified: 0.0.0.0/8
    • broadcast: 255.255.255.255/32
    • multicast: 224.0.0.0/4
    • linkLocal: 169.254.0.0/16
    • loopback: 127.0.0.0/8
    • carrierGradeNat: 100.64.0.0/10
    • private: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
    • reserved: Various RFC-defined ranges
    • as112, amt
    const ipaddr = require('ipaddr.js');
    const addr = ipaddr.parse('127.0.0.1');
    
    // Check if address is in a special range
    const range = addr.range();
    console.log(range); // 'loopback'
  3. Access IPv6 special ranges

    main

    The IPv6 class provides a SpecialRanges property containing predefined subnets for common IPv6 address types. You can use these with ipaddr.subnetMatch() to identify the type of an address.

    Key ranges include:

    • unspecified: ::/128
    • linkLocal: fe80::/10
    • multicast: ff00::/8
    • loopback: ::1/128
    • uniqueLocal: fc00::/7
    • ipv4Mapped: ::ffff:0:0/96
    • 6to4: 2002::/16
    • teredo: 2001:db8::/32
    const ipaddr = require('ipaddr.js');
    const addr = ipaddr.parse('::1');
    
    const range = addr.range();
    console.log(range); // 'loopback'
  4. Validate IP addresses and CIDR notation

    main

    Use these methods to check if a string is a valid address or CIDR range. These methods return a boolean and never throw.

    ipaddr.isValid('192.168.1.1');   // => true
    ipaddr.isValid('999.0.0.1');    // => false
    
    ipaddr.isValidCIDR('192.168.0.0/24');  // => true
    ipaddr.isValidCIDR('192.168.0.1/33'); // => false
  5. Convert and format IPv6 addresses

    main

    The IPv6 instance provides several methods for different string and byte representations:

    • addr.toByteArray(): Returns a 16-byte array in network byte order.
    • addr.toFixedLengthString(): Returns the address with all eight groups expanded to four hex digits (no :: compression).
    • addr.toNormalizedString(): Returns the address with all eight groups in lowercase hex (no :: compression).
    • addr.toRFC5952String(): Returns the canonical format (lowercase, leading zeros omitted, longest run of zeros replaced by ::).
    • addr.toString(): Returns the compact string representation (identical to toRFC5952String()).
    • addr.toIPv4Address(): Converts an IPv4-mapped IPv6 address to its IPv4 equivalent (throws if not mapped).
    const addr = ipaddr.parse('2001:db8::1');
    
    addr.toByteArray();           // => [0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
    addr.toFixedLengthString();  // => '2001:0db8:0000:0000:0000:0000:0000:0001'
    addr.toRFC5952String();      // => '2001:db8::1'
    addr.toString();             // => '2001:db8::1'
  6. Handle IPv4-mapped IPv6 addresses with ipaddr.process()

    main

    Use ipaddr.process(string) to automatically convert IPv4-mapped IPv6 addresses (e.g., ::ffff:192.168.1.1) into their IPv4 equivalents. This is particularly useful when handling dual-stack IPv6 sockets where IPv4 clients appear as mapped IPv6 addresses.

    ipaddr.process('::ffff:192.168.1.1').toString(); // => '192.168.1.1'
    ipaddr.process('::ffff:192.168.1.1').kind();     // => 'ipv4'
    ipaddr.process('2001:db8::1').kind();            // => 'ipv6'
  7. Calculate IPv4 network, broadcast, and subnet mask information

    main

    Use these static methods to derive network properties from CIDR strings:

    • ipaddr.IPv4.broadcastAddressFromCIDR(string): Returns the broadcast address for the given CIDR block.
    • ipaddr.IPv4.networkAddressFromCIDR(string): Returns the network address for the given CIDR block.
    • ipaddr.IPv4.subnetMaskFromPrefixLength(prefix): Returns the IPv4 subnet mask corresponding to the given CIDR prefix length.
    ipaddr.IPv4.broadcastAddressFromCIDR('192.168.1.0/24').toString(); // => '192.168.1.255'
    ipaddr.IPv4.networkAddressFromCIDR('192.168.1.42/24').toString(); // => '192.168.1.0'
    ipaddr.IPv4.subnetMaskFromPrefixLength(24).toString(); // => '255.255.255.0'
  8. Parse IPv4 addresses and CIDR blocks

    main

    Convert IPv4 strings into IPv4 objects or extract CIDR components.

    • ipaddr.IPv4.parse(string): Parses a string into an IPv4 object. Supports standard dotted-decimal and POSIX inet_aton formats (hex, octal, three-part, two-part, or single-value notation). Throws if the string is invalid.
    • ipaddr.IPv4.parseCIDR(string): Parses an IPv4 CIDR address and returns a tuple: [IPv4, prefixLength]. Throws if the input is invalid.
    ipaddr.IPv4.parse('192.168.1.1').toString();   // => '192.168.1.1'
    ipaddr.IPv4.parse('0xc0.168.1.1').toString();  // => '192.168.1.1'
    
    const [addr, prefix] = ipaddr.IPv4.parseCIDR('192.168.1.0/24');
    addr.toString(); // => '192.168.1.0'
    prefix;          // => 24
  9. Perform subnet matching for IPv6

    main

    The addr.subnetMatch(rangeList[, defaultName]) method is an instance-method shorthand for ipaddr.subnetMatch(addr, rangeList, defaultName). It checks which range in a provided object the address belongs to.

    rangeList is an object where keys are names and values are [IPv6, prefixLength] pairs.

    Example:

    const addr = ipaddr.parse('2001:db8::1');
    const ranges = { documentation: [ipaddr.parse('2001:db8::'), 32] };
    addr.subnetMatch(ranges); // => 'documentation'
  10. Calculate IPv6 network and broadcast addresses

    main

    The ipaddr.IPv6 class provides static methods to derive network information from CIDR strings:

    • ipaddr.IPv6.broadcastAddressFromCIDR(string): Returns the last address in the CIDR block.
    • ipaddr.IPv6.networkAddressFromCIDR(string): Returns the network address for the CIDR block.
    • ipaddr.IPv6.subnetMaskFromPrefixLength(prefix): Returns the subnet mask for a given prefix length.
    ipaddr.IPv6.broadcastAddressFromCIDR('2001:db8::/120').toString(); // => '2001:db8::ff'
    ipaddr.IPv6.networkAddressFromCIDR('2001:db8::42/32').toString(); // => '2001:db8::'
    ipaddr.IPv6.subnetMaskFromPrefixLength(64).toString(); // => 'ffff:ffff:ffff:ffff::'
  11. Construct an address from a byte array with fromByteArray()

    main

    Create an IPv4 or IPv6 address from a byte array in network byte order (MSB first).

    • For IPv4: provide an array of 4 bytes.
    • For IPv6: provide an array of 16 bytes.

    Throws if the array length is not 4 or 16.

    ipaddr.fromByteArray([127, 0, 0, 1]).toString(); // => '127.0.0.1'
    
    ipaddr.fromByteArray([
      0x20, 0x01, 0x0d, 0xb8,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x01,
    ]).toString(); // => '2001:db8::1'