PHP's inet_pton in JavaScript

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
module.exports = function inet_pton (a) { // eslint-disable-line camelcase
// discuss at: http://locutus.io/php/inet_pton/
// original by: Theriault (https://github.com/Theriault)
// 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'
var r
var m
var x
var i
var j
var f = String.fromCharCode
// IPv4
m = a.match(/^(?:\d{1,3}(?:\.|$)){4}/)
if (m) {
m = m[0].split('.')
m = f(m[0]) + f(m[1]) + f(m[2]) + f(m[3])
// Return if 4 bytes, otherwise false.
return m.length === 4 ? m : false
}
r = /^((?:[\da-f]{1,4}(?::|)){0,8})(::)?((?:[\da-f]{1,4}(?::|)){0,8})$/
// IPv6
m = a.match(r)
if (m) {
// Translate each hexadecimal value.
for (j = 1; j < 4; j++) {
// Indice 2 is :: and if no length, continue.
if (j === 2 || m[j].length === 0) {
continue
}
m[j] = m[j].split(':')
for (i = 0; i < m[j].length; i++) {
m[j][i] = parseInt(m[j][i], 16)
// Would be NaN if it was blank, return false.
if (isNaN(m[j][i])) {
// Invalid IP.
return false
}
m[j][i] = f(m[j][i] >> 8) + f(m[j][i] & 0xFF)
}
m[j] = m[j].join('')
}
x = m[1].length + m[3].length
if (x === 16) {
return m[1] + m[3]
} else if (x < 16 && m[2].length > 0) {
return m[1] + (new Array(16 - x + 1))
.join('\x00') + m[3]
}
}
// Invalid IP
return false
}
[ 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 Browserify, webpack or rollup.js.

ES5/ES6

This function targets ES5, but as of Locutus 2.0.2 we also support ES6 functions. Locutus transpiles 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.

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'

« More PHP network functions