JavaScript inet_ntop
Converts a packed inet address to a human readable IP address string
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 | function inet_ntop (a) { // Converts a packed inet address to a human readable IP address string // // version: 1109.2015 // discuss at: http://phpjs.org/functions/inet_ntop // + original by: Theriault // * example 1: inet_ntop('\x7F\x00\x00\x01'); // * returns 1: '127.0.0.1' // * example 2: inet_ntop('\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1'); // * returns 2: '::1' var i = 0, m = '', c = []; a += ''; if (a.length === 4) { // IPv4 return [ a.charCodeAt(0), a.charCodeAt(1), a.charCodeAt(2), a.charCodeAt(3)].join('.'); } else if (a.length === 16) { // IPv6 for (i = 0; i < 16; i++) { c.push(((a.charCodeAt(i++) << 8) + a.charCodeAt(i)).toString(16)); } return c.join(':').replace(/((^|:)0(?=:|$))+:?/g, function (t) { m = (t.length > m.length) ? t : m; return t; }).replace(m || ' ', '::'); } else { // Invalid length return false; } } |
Examples
» Example 1
Running
1 | inet_ntop('\x7F\x00\x00\x01'); |
Should return
1 | '127.0.0.1' |
» Example 2
Running
1 | inet_ntop('\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1'); |
Should return
1 | '::1' |
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 inet_ntop goodness in JavaScript.

rimal
16 Sep '11