Home > Software design >  IP address to Int
IP address to Int

Time:09-01

So I am having an issue with converting IPv4 and IPv6 to Int, I however have found this handy Go script which does it, however I need it for NodeJS.

I have tried the plugins in NPM including ip2int but it seems to be broken, and only work for IPv4.

I am wondering if anyone would know how to convert GO into Javascript for nodeJS. As I know the following code works in Go.

package main

import (
    "fmt"
    "math/big"
    "net"
)

func Ip2Int(ip net.IP) *big.Int {
    i := big.NewInt(0)
    i.SetBytes(ip)
    return i
}

func main() {
    fmt.Println(Ip2Int(net.ParseIP("20.36.77.12").To4()).String())
    fmt.Println(Ip2Int(net.ParseIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334").To16()).String())
}

The reason why we need to parse the IP addresses to int is so that when we receive the IP address we can search to see if that IP address is inside one of the ranges of IP addresses that we have collected.

For example RAPD returns

 "startAddress": "35.192.0.0",
  "endAddress": "35.207.255.255",

so if we convert both of those to int we can store them in our DB and do a gte or lte search and see if the IP address is in between any of the stored values.

Here is the answer:

https://jsfiddle.net/russellharrower/vxhwLmqr/

var ip = '2001:0db8:0:0:8d3:0:0:0';
//var ip = '35.192.0.0'

// simulate your address.binaryZeroPad(); method
var parts = [];
ip.split(/[.,\/ :]/).forEach(function(it) {
    var bin = parseInt(it, 16).toString(2);
    while (bin.length < 16) {
        bin = "0"   bin;
    }
    parts.push(bin);
})
var bin = parts.join("");

// Use BigInteger library
var dec = bigInt(bin, 2).toString();
console.log(dec);

CodePudding user response:

See this solution.

For IPv4 use:

ipv4.split('.').reduce(function(int, value) { return int * 256    value })

For IPv6 you first need to parse the hex values and the hex values represent 2 bytes:

ipv6.split(':').map(str => Number('0x' str)).reduce(function(int, value) { return int * 65536    value })

I've also added the ipv6 solution to the referenced gist.

CodePudding user response:

Javascript (vanilla) program:

function ipToInt(value) {
  return Number(value.replace(/[a-z]|:|\./g, ""))
}

const ip1 = "2001:0db8:0:0:8d3:0:0:0"
const ip2 = "35.192.0.0"

console.log("IPv6", ipToInt(ip1))
console.log("IPv4", ipToInt(ip2))
  • Related