Content · Programming · PHP

PHP ip2long() Function: Usage and Examples

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

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

Use ip2long() when you need to converts an IPv4 address into its integer representation in a PHP application. The examples below show the actual operation and its limitations.

What Is ip2long() in PHP?

Converts an IPv4 address into its integer representation. The exact signature supported by your installation depends on its PHP version and enabled extensions.

Its syntax is:

ip2long(string $ip): int|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 sprintf("%u",ip2long("192.0.2.1"));

Output:

3221225985

Example 2: Different Input or Behavior

<?php

var_dump(ip2long("not-an-ip") === false);

Output:

bool(true)

Practical Example: Applying the Function

<?php

$ipAddress = "203.0.113.5"; $encoded = ip2long($ipAddress); echo $encoded === false ? "Invalid" : long2ip($encoded);

Output:

203.0.113.5

Important Behavior and Edge Cases

Signed integer representations differ across platforms; this function does not handle IPv6.

Comparison With Related Functions

ApproachDifference
ip2long()Converts an IPv4 address into its integer representation.
Related operationinet_pton() supports both IPv4 and IPv6 in a packed binary representation.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationSigned integer representations differ across platforms; this function does not handle IPv6.
Confusing this function with a related operationinet_pton() supports both IPv4 and IPv6 in a packed binary representation.

Key Takeaways

  • Converts an IPv4 address into its integer representation.
  • Signed integer representations differ across platforms; this function does not handle IPv6.
  • inet_pton() supports both IPv4 and IPv6 in a packed binary representation.

Use ip2long() 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.