Content · Programming · PHP

PHP inet_pton() Function: Usage and Examples

Understand PHP inet_pton() with three examples, return behavior, important pitfalls, and related operations.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Use inet_pton() when you need to converts a readable IPv4 or IPv6 address into packed binary bytes in a PHP application. The examples below show the actual operation and its limitations.

What Is inet_pton() in PHP?

Converts a readable IPv4 or IPv6 address into packed binary bytes. The exact signature supported by your installation depends on its PHP version and enabled extensions.

Its syntax is:

inet_pton(string $ip): string|false

Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.

Example 1: Basic Usage

<?php

echo bin2hex(inet_pton("127.0.0.1"));

Output:

7f000001

Example 2: Different Input or Behavior

<?php

echo strlen(inet_pton("2001:db8::1"));

Output:

16

Practical Example: Applying the Function

<?php

$submittedAddress = "192.0.2.10"; $binaryAddress = inet_pton($submittedAddress); echo $binaryAddress === false ? "Invalid" : "Valid IP";

Output:

Valid IP

Important Behavior and Edge Cases

Returns false for invalid IP text; binary output should not be printed directly in HTML.

Comparison With Related Functions

ApproachDifference
inet_pton()Converts a readable IPv4 or IPv6 address into packed binary bytes.
Related operationinet_ntop() converts packed binary IP data back to human-readable text.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationReturns false for invalid IP text; binary output should not be printed directly in HTML.
Confusing this function with a related operationinet_ntop() converts packed binary IP data back to human-readable text.

Key Takeaways

  • Converts a readable IPv4 or IPv6 address into packed binary bytes.
  • Returns false for invalid IP text; binary output should not be printed directly in HTML.
  • inet_ntop() converts packed binary IP data back to human-readable text.

Use inet_pton() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.

Share this resourceSend this page to someone who may find it useful.