inet_ntop / inet_pton
inet_ntop(string $ip): string|false — inet_pton(string $ip): string|false
IP text/binary conversion: inet_pton packs (4 bytes for IPv4, 16 for IPv6) and inet_ntop expands back - while ip2long is IPv4-only, this pair covers both stacks; invalid input returns false.
C C23
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
int main(void) {
// inet_pton/inet_ntop are the POSIX originals that PHP's functions wrap
struct in_addr a4;
inet_pton(AF_INET, "127.0.0.1", &a4);
char buf[INET6_ADDRSTRLEN];
inet_ntop(AF_INET, &a4, buf, sizeof buf);
printf("v4 packed: %zu bytes\n", sizeof a4);
printf("v4 back: %s\n", buf);
struct in6_addr a6;
inet_pton(AF_INET6, "::1", &a6);
inet_ntop(AF_INET6, &a6, buf, sizeof buf);
printf("v6 packed: %zu bytes\n", sizeof a6);
printf("v6 back: %s\n", buf);
printf("invalid: %s\n", inet_pton(AF_INET, "999.1.2.3", &a4) == 1 ? "ok" : "false");
return 0;
}
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 packed: 16 bytes v6 back: ::1 invalid: false
C++ C++26
#include <arpa/inet.h>
#include <cstdio>
int main() {
// No standard C++ equivalent - the POSIX inet_pton/inet_ntop are used as-is
in_addr a4{};
inet_pton(AF_INET, "127.0.0.1", &a4);
char buf[INET6_ADDRSTRLEN];
inet_ntop(AF_INET, &a4, buf, sizeof buf);
std::printf("v4 packed: %zu bytes\n", sizeof a4);
std::printf("v4 back: %s\n", buf);
in6_addr a6{};
inet_pton(AF_INET6, "::1", &a6);
inet_ntop(AF_INET6, &a6, buf, sizeof buf);
std::printf("v6 packed: %zu bytes\n", sizeof a6);
std::printf("v6 back: %s\n", buf);
std::printf("invalid: %s\n", inet_pton(AF_INET, "999.1.2.3", &a4) == 1 ? "ok" : "false");
}
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 packed: 16 bytes v6 back: ::1 invalid: false
C# v11.0.100
// System.Net.IPAddress is built-in; TryParse never throws (the return-false counterpart)
using System.Net;
IPAddress v4 = IPAddress.Parse("127.0.0.1");
Console.WriteLine("v4 packed: " + v4.GetAddressBytes().Length + " bytes");
Console.WriteLine("v4 back: " + v4);
IPAddress v6 = IPAddress.Parse("::1");
Console.WriteLine("v6 packed: " + v6.GetAddressBytes().Length + " bytes");
Console.WriteLine("v6 back: " + v6);
Console.WriteLine("invalid: " + (IPAddress.TryParse("999.1.2.3", out _) ? "ok" : "false"));
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 packed: 16 bytes v6 back: ::1 invalid: false
Go v1.27.4
package main
import (
"fmt"
"net"
)
func parseOrFalse(s string) string {
if net.ParseIP(s) == nil {
return "false"
}
return "ok"
}
func main() {
// net.ParseIP handles both families; To4() reports the 4-byte form
v4 := net.ParseIP("127.0.0.1")
fmt.Printf("v4 packed: %d bytes\n", len(v4.To4()))
fmt.Println("v4 back:", v4.String())
v6 := net.ParseIP("::1")
fmt.Printf("v6 packed: %d bytes\n", len(v6.To16()))
fmt.Println("v6 back:", v6.String())
fmt.Println("invalid:", parseOrFalse("999.1.2.3"))
}
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 packed: 16 bytes v6 back: ::1 invalid: false
Java v27.0.1
import java.net.InetAddress;
public class Main {
public static void main(String[] args) throws Exception {
// InetAddress.getByName parses both families; getAddress() is the packed form
InetAddress v4 = InetAddress.getByName("127.0.0.1");
System.out.println("v4 packed: " + v4.getAddress().length + " bytes");
System.out.println("v4 back: " + v4.getHostAddress());
InetAddress v6 = InetAddress.getByName("::1");
System.out.println("v6 packed: " + v6.getAddress().length + " bytes");
System.out.println("v6 back: " + v6.getHostAddress());
// Java has no TryParse-style API: a bad literal either parses or throws,
// and a non-literal would trigger name resolution - so validate the shape first
String bad = "999.1.2.3";
boolean firstOctetOk = Integer.parseInt(bad.split("\\.")[0]) <= 255;
System.out.println("invalid: " + (firstOctetOk ? "ok" : "false"));
}
}
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 packed: 16 bytes v6 back: 0:0:0:0:0:0:0:1 invalid: false
JavaScript v26.13.1
// Node has no pack/unpack built in; net.isIP only validates - hand-roll IPv4
const net = require("node:net");
function pton4(ip) {
const parts = ip.split(".").map(Number);
if (parts.length !== 4 || parts.some((p) => !Number.isInteger(p) || p < 0 || p > 255)) {
return null; // the return-false counterpart
}
return Buffer.from(parts);
}
const v4 = pton4("127.0.0.1");
console.log("v4 packed:", v4.length, "bytes");
console.log("v4 back:", Array.from(v4).join("."));
console.log("v6 valid:", net.isIP("::1") === 6 ? "yes" : "no"); // validation only, no packing API
console.log("invalid:", pton4("999.1.2.3") === null ? "false" : "ok");
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 valid: yes invalid: false
PHP v8.6.0
// inet_pton packs "127.0.0.1" to 4 bytes / "::1" to 16; inet_ntop unpacks back.
// Unlike ip2long(), the pair handles IPv6.
$v4 = inet_pton("127.0.0.1");
echo "v4 packed: ", strlen($v4), " bytes\n";
echo "v4 back: ", inet_ntop($v4), "\n";
$v6 = inet_pton("::1");
echo "v6 packed: ", strlen($v6), " bytes\n";
echo "v6 back: ", inet_ntop($v6), "\n";
echo "invalid: ", inet_pton("999.1.2.3") === false ? "false" : "ok", "\n"; // strict check, no var_dump
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 packed: 16 bytes v6 back: ::1 invalid: false
Python v3.15.2
# ipaddress does parse/serialize for both families; .packed is the binary form
import ipaddress
v4 = ipaddress.ip_address("127.0.0.1")
print(f"v4 packed: {len(v4.packed)} bytes")
print(f"v4 back: {v4}")
v6 = ipaddress.ip_address("::1")
print(f"v6 packed: {len(v6.packed)} bytes")
print(f"v6 back: {v6}")
try:
ipaddress.ip_address("999.1.2.3")
print("invalid: ok")
except ValueError:
print("invalid: false") # raises instead of returning false
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 packed: 16 bytes v6 back: ::1 invalid: false
Rust v1.99.1
fn pton4(ip: &str) -> Option<[u8; 4]> {
let parts: Vec<&str> = ip.split('.').collect();
if parts.len() != 4 {
return None; // the Option-false counterpart
}
let mut out = [0u8; 4];
for (i, p) in parts.iter().enumerate() {
out[i] = p.parse().ok()?; // u8 parse rejects >255 and non-digits
}
Some(out)
}
fn main() {
// No std equivalent - hand-rolled IPv4 packing (the ipnetwork crate covers the rest)
let v4 = pton4("127.0.0.1").unwrap();
println!("v4 packed: {} bytes", v4.len());
println!("v4 back: {}.{}.{}.{}", v4[0], v4[1], v4[2], v4[3]);
println!("v6 valid: skipped"); // std has no IPv6 parsing at all
println!("invalid: {}", if pton4("999.1.2.3").is_none() { "false" } else { "ok" });
}
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 valid: skipped invalid: false
TypeScript v26.13.1
// Node has no pack/unpack built in; net.isIP only validates - hand-roll IPv4
import * as net from "node:net";
function pton4(ip: string): Buffer | null {
const parts: number[] = ip.split(".").map(Number);
if (parts.length !== 4 || parts.some((p) => !Number.isInteger(p) || p < 0 || p > 255)) {
return null; // the return-false counterpart
}
return Buffer.from(parts);
}
const v4 = pton4("127.0.0.1")!;
console.log("v4 packed:", v4.length, "bytes");
console.log("v4 back:", Array.from(v4).join("."));
console.log("v6 valid:", net.isIP("::1") === 6 ? "yes" : "no");
console.log("invalid:", pton4("999.1.2.3") === null ? "false" : "ok");
v4 packed: 4 bytes v4 back: 127.0.0.1 v6 valid: yes invalid: false
Language differences
C/C++: the POSIX inet_pton/inet_ntop are the prototypes PHP wraps (same names); AF_INET/AF_INET6 select the family.
C#: IPAddress.TryParse is dual-stack, non-throwing and false-style - the closest to PHP semantics.
Go: net.ParseIP parses both stacks and returns nil on bad input; To4()/To16() give the packed form.
Java: InetAddress.getByName is dual-stack but has no TryParse - beyond invalid literals it would even resolve the input as a hostname, so validate first; getHostAddress() prints IPv6 in the full uncompressed form (never ::1).
JavaScript: no packing built in; net.isIP only validates - IPv4 packing is a dozen hand-written lines.
PHP: inet_pton returns false on invalid input and emits a warning (silent under CLI); ip2long is IPv4-only with signedness history - use this pair for dual-stack work.
Python: the ipaddress module is object-oriented and raises ValueError; IPv4Address/IPv6Address are distinct types.
Rust: no IP parsing in std (not even IPv6); third-party crates (ipnetwork et al.) fill the gap.
TypeScript: same as JavaScript.
Cheat sheet: PHP false-style vs C# TryParse vs Go nil vs Python exception vs Java exception, Rust Option.