Current Location: Home> Latest Articles> How to Easily Convert an IP Address to an Integer Using the ip2long Function in PHP

How to Easily Convert an IP Address to an Integer Using the ip2long Function in PHP

gitbox 2025-06-08

In network programming, handling IP addresses is a very common task. IP addresses usually appear as strings, such as "192.168.0.1", but in some situations, we need to convert them into integer values for storage, comparison, or calculation. PHP provides a very convenient built-in function, ip2long, which makes this conversion easy.


Introduction to the ip2long Function

ip2long is a built-in PHP function that converts a dotted-decimal IPv4 address to its corresponding integer form. The resulting integer can be used for database storage, range checks, or other network-related operations.

Syntax

ip2long(string $ip): int|false
  • $ip: The string representation of the IPv4 address to be converted.

  • The return value is the corresponding integer, or false if the IP address is invalid.


Usage Example

Here is a simple example demonstrating how to use ip2long to convert an IP address to an integer:

<?php
$ip = "192.168.0.1";
$ipLong = ip2long($ip);
<p>if ($ipLong !== false) {<br>
echo "The integer corresponding to IP address {$ip} is: {$ipLong}";<br>
} else {<br>
echo "Invalid IP address.";<br>
}<br>
?><br>

Output:

The integer corresponding to IP address 192.168.0.1 is: 3232235521

Real-world Use Cases for ip2long

  1. Database Storage Optimization
    Converting IP addresses to integers before storing them in a database helps reduce storage space and speed up query performance.

  2. IP Address Range Comparison
    For example, to determine whether an IP address is within a specific subnet, you can compare the integer values.

  3. Security Filtering
    In firewalls or access control lists, using integer IPs allows for fast filtering.


Reverse Function: long2ip

If you want to convert an integer-based IP address back into its string format, you can use PHP's long2ip function.

Example:

<?php
$ipLong = 3232235521;
$ip = long2ip($ipLong);
<p>echo "The IP address corresponding to the integer {$ipLong} is: {$ip}";<br>
?><br>

Output:

The IP address corresponding to the integer 3232235521 is: 192.168.0.1

Important Notes

  • ip2long only supports IPv4 addresses and does not work with IPv6.

  • The returned integer is a signed 32-bit integer, which may lead to negative values on certain 32-bit systems.

  • If the IP address format is incorrect, the function will return false, so you should always perform validation when using it.


Understanding and mastering the ip2long function will help you handle IP addresses more efficiently and concisely. Combined with database and network programming requirements, this small function will be a useful tool in your development toolkit.