JavaScript long2ip
Converts an (IPv4) Internet network address into a string in Internet standard dotted format
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 20 | function long2ip ( proper_address ) { // Converts an (IPv4) Internet network address into a string in Internet standard dotted format // // version: 1008.1718 // discuss at: http://phpjs.org/functions/long2ip // + original by: Waldo Malqui Silva // * example 1: long2ip( 3221234342 ); // * returns 1: '192.0.34.166' var output = false; if ( !isNaN( proper_address ) && ( proper_address >= 0 || proper_address <= 4294967295 ) ) { output = Math.floor(proper_address / Math.pow( 256, 3 ) ) + '.' + Math.floor( ( proper_address % Math.pow( 256, 3 ) ) / Math.pow( 256, 2 ) ) + '.' + Math.floor( ( ( proper_address % Math.pow( 256, 3 ) ) % Math.pow( 256, 2 ) ) / Math.pow( 256, 1 ) ) + '.' + Math.floor( ( ( ( proper_address % Math.pow( 256, 3 ) ) % Math.pow( 256, 2 ) ) % Math.pow( 256, 1 ) ) / Math.pow( 256, 0 ) ); } return output; } |
Examples
Running
1 | long2ip( 3221234342 ); |
Should return
1 | '192.0.34.166' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have long2ip goodness in JavaScript.
Cool idea. But this doesn't work. If you use ip2long in php, and get the result of that and pass it to this long2ip javascript function, what you get is NOT the original IP you started with. If you add (256^4)/2 to the long, you'll get the 2nd, 3rd and 4th sections correct but the first section of the IP will still be off.
long2ip/php accepts the signed int, but apparently the javascript version is looking for an unsigned int


Kevin van Zonneveld
4 Sep '09
On 64 bits system ip2long ONLY RETURNS POSITIVE VALUES
so
<?php
echo ip2long('200.200.200.200');
?>
will output -926365496 on a 32 bits system and 3368601800 on a 64 bits system
So basically only use this in the confinement of 1 process, or use a methods to get consistent numbers like sprintf('%u') before transporting to database/client/whatever