Use PHP functions in JavaScript

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;
    }
}
external links: original PHP docs | raw js source

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.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
rimal
16 Sep '11 Permalink

q  what's the fuck?


Contribute a New function

More functions

In this category

» inet_ntop
inet_pton
ip2long
long2ip
setcookie
setrawcookie

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !