PHP's inet_pton in JavaScript

How to use

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

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_pton('::')'\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0'
2inet_pton('127.0.0.1')'\x7F\x00\x00\x01'

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

module.exports = function inet_pton(a) {
// discuss at: https://locutus.io/php/inet_pton/
// original by: Theriault (https://github.com/Theriault)
// improved by: alromh87 and JamieSlome
// example 1: inet_pton('::')
// returns 1: '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0'
// example 2: inet_pton('127.0.0.1')
// returns 2: '\x7F\x00\x00\x01'

let m
let i
let j
const f = String.fromCharCode

// IPv4
m = a.match(/^(?:\d{1,3}(?:\.|$)){4}/)
if (m) {
m = m[0].split('.')
m = f(m[0], m[1], m[2], m[3])
// Return if 4 bytes, otherwise false.
return m.length === 4 ? m : false
}

// IPv6
if (a.length > 39) {
return false
}

m = a.split('::')

if (m.length > 2) {
return false
} // :: can't be used more than once in IPv6.

const reHexDigits = /^[\da-f]{1,4}$/i

for (j = 0; j < m.length; j++) {
if (m[j].length === 0) {
// Skip if empty.
continue
}
m[j] = m[j].split(':')
for (i = 0; i < m[j].length; i++) {
let hextet = m[j][i]
// check if valid hex string up to 4 chars
if (!reHexDigits.test(hextet)) {
return false
}

hextet = parseInt(hextet, 16)

// Would be NaN if it was blank, return false.
if (isNaN(hextet)) {
// Invalid IP.
return false
}
m[j][i] = f(hextet >> 8, hextet & 0xff)
}
m[j] = m[j].join('')
}

return m.join('\x00'.repeat(16 - m.reduce((tl, m) => tl + m.length, 0)))
}

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