PHP's inet_pton in JavaScript

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

module.exports = function inet_pton (a) { // eslint-disable-line camelcase
// discuss at:
// original by: 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('')
// 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.
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)))
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/php/network/inet_pton'). You could also require the network module in full so that you could access network.inet_pton instead.

If you intend to target the browser, you can then use a module bundler such as Parcel, webpack, Browserify, or rollup.js. This can be important because Locutus allows modern JavaScript in the source files, meaning it may not work in all browsers without a build/transpile step. Locutus does transpile all functions to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.


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

« More PHP network functions