UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

102 lines (89 loc) 3.01 kB
--- layout: page title: "JavaScript inet_pton function" comments: true sharing: true footer: true alias: - /functions/view/inet_pton:883 - /functions/view/inet_pton - /functions/view/883 - /functions/inet_pton:883 - /functions/883 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's inet_pton {% codeblock network/inet_pton.js lang:js https://raw.github.com/kvz/phpjs/master/functions/network/inet_pton.js raw on github %} function inet_pton (a) { // From: http://phpjs.org/functions // + original by: 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, m, x, i, j, f = String.fromCharCode; m = a.match(/^(?:\d{1,3}(?:\.|$)){4}/); // IPv4 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})$/; m = a.match(r); // IPv6 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])) { return false; // Invalid IP. } 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]; } } return false; // Invalid IP. } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/network/inet_pton.js) Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure. Please also note that php.js offers community built functions and goes by the [McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/network/inet_pton.js) ### Example 1 This code {% codeblock lang:js example %} inet_pton('::'); {% endcodeblock %} Should return {% codeblock lang:js returns %} '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0' {% endcodeblock %} ### Example 2 This code {% codeblock lang:js example %} inet_pton('127.0.0.1'); {% endcodeblock %} Should return {% codeblock lang:js returns %} '\x7F\x00\x00\x01' {% endcodeblock %} ### Other PHP functions in the network extension {% render_partial _includes/custom/network.html %}