Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.
How to use
Install via yarn add locutus and import:
import { inet_pton } from 'locutus/php/network/inet_pton'.
Or with CommonJS: const { inet_pton } = require('locutus/php/network/inet_pton')
Use a bundler that supports tree-shaking so you only ship the functions you actually use.
Vite,
webpack,
Rollup, and
Parcel
all handle this. For server-side use this is less of a concern.
Examples
These examples are extracted from test cases that automatically verify our functions against their native counterparts.
#
code
expected result
1
inet_pton('::')
'\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0'
2
inet_pton('127.0.0.1')
'\x7F\x00\x00\x01'
Here's what our current TypeScript equivalent to PHP's inet_pton looks like.
if (segments.length > 2) { returnfalse } // :: can't be used more than once in IPv6.
const reHexDigits = /^[\da-f]{1,4}$/i
constpackedSegments: string[] = [] for (const segment of segments) { if (segment.length === 0) { packedSegments.push('') continue } const hextets = segment.split(':') let packed = '' for (const hextetSource of hextets) { const hextet = hextetSource // check if valid hex string up to 4 chars if (!reHexDigits.test(hextet)) { returnfalse }
const parsedHextet = parseInt(hextet, 16)
// Would be NaN if it was blank, return false. if (Number.isNaN(parsedHextet)) { // Invalid IP. returnfalse } packed += f(parsedHextet >> 8, parsedHextet & 0xff) } packedSegments.push(packed) }
const bytesLength = packedSegments.reduce((total, part) => total + part.length, 0) if (bytesLength > 16) { returnfalse }
if (segments.length > 2) { returnfalse } // :: can't be used more than once in IPv6.
const reHexDigits = /^[\da-f]{1,4}$/i
const packedSegments = [] for (const segment of segments) { if (segment.length === 0) { packedSegments.push('') continue } const hextets = segment.split(':') let packed = '' for (const hextetSource of hextets) { const hextet = hextetSource // check if valid hex string up to 4 chars if (!reHexDigits.test(hextet)) { returnfalse }
const parsedHextet = parseInt(hextet, 16)
// Would be NaN if it was blank, return false. if (Number.isNaN(parsedHextet)) { // Invalid IP. returnfalse } packed += f(parsedHextet >> 8, parsedHextet & 0xff) } packedSegments.push(packed) }
const bytesLength = packedSegments.reduce((total, part) => total + part.length, 0) if (bytesLength > 16) { returnfalse }
Locutus is a community effort following
The McDonald's Theory:
we ship first iterations, hoping others will improve them.
If you see something that could be better, we'd love your contribution.