Search code examples
node.js

How to convert a hyphenated IP range to CIDR in Node.js?


I have a hyphenated IP range, and I need to convert it to CIDR notation, for example:

input: 70.103.242.28-70.103.242.30 output: 70.103.242.28/31, 70.103.242.30/32

Python has a library for it (ipaddress):

cidr = ipaddress.summarize_address_range(start_ip, end_ip)

Looking for something similar in Node.js, but unable to find it. I would rather use a library for it than implement it on my own. Looked into netmask, ip-cidr, ip6, ip libraries, but it doesn't look like any of those support it.


Solution

  • I think you need to use ip-subnet-calculator module:

    const SubnetCalculator = require('ip-subnet-calculator');
    
    const ipRange = '192.168.0.1-192.168.0.10';
    const [startIp, endIp] = ipRange.split('-');
    
    const subnet = SubnetCalculator.calculate(startIp, endIp);
    console.log(subnet);
    

    Output:

    [
        {
            ipLow: 3232235521,
            ipLowStr: "192.168.0.1",
            ipHigh: 3232235521,
            ipHighStr: "192.168.0.1",
            prefixMask: 4294967295,
            prefixMaskStr: "255.255.255.255",
            prefixSize: 32,
            invertedMask: 0,
            invertedMaskStr: "0.0.0.0",
            invertedSize: 0
        },
        // ...
    ]