PHP's inet_ntop in JavaScript

How to use

You you can install via yarn add locutus and require this function via const inet_ntop = require('locutus/php/network/inet_ntop').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1inet_ntop('\x7F\x00\x00\x01')'127.0.0.1'

Here’s what our current JavaScript equivalent to PHP's inet_ntop looks like.

module.exports = function inet_ntop(a) {
// discuss at: https://locutus.io/php/inet_ntop/
// original by: Theriault (https://github.com/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'

let i = 0
let m = ''
const 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
}
}

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP network functions


Star