## Convert IP Address to numeric (JS)

I’ve been using some fancy functions in SQL to convert to/from an IP Address and Mask – but have needed to do the same within JavaScript.

This is a requirement based on some MySQL functions – eg. INET_NTOA and INET_ATON.

This first one will take an input value – eg. 255.240.0.0 – and return a number (BIGINT / INT64 for calculations – or storing in a database – as we’re needing to do.

```    function convertIpToNumeric(ipAddress) {
var arrIp = ipAddress.split(&quot;.&quot;);

var segment1 = parseInt(arrIp);
var segment2 = parseInt(arrIp);
var segment3 = parseInt(arrIp);
var segment4 = parseInt(arrIp);

//reverse order calc
//eg. 255.255.240.0     &lt;-- start at the end
// 0 + (240*256) + (255*65536) + (255*16777216)
var calc = segment4 + (segment3 * 256) + (segment2 * 65536) + (segment1 * 16777216);

return calc;

}

```

And – if needing to do the opposite – you can use the following function.

This will take an input value – eg. 167772161 – and return the resultant IP Address :

```function convertNumericToIp(bigNumber) {

var Octet1 = Math.floor(bigNumber / 16777216)
var RestOfIP = bigNumber - (Octet1 * 16777216)

var Octet2 = Math.floor(RestOfIP / 65536)
var RestOfIP = RestOfIP - (Octet2 * 65536)

var Octet3 = Math.floor(RestOfIP / 256)

var Octet4 = RestOfIP - (Octet3 * 256)

var returnValue = Octet1 + &quot;.&quot; + Octet2 + &quot;.&quot; + Octet3 + &quot;.&quot; + Octet4;

return returnValue;

}

```
Advertisements