Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP Network inet_ntop() Function



The PHP Network inet_ntop() function is used to convert an IP address into a readable string. It can handle both IPv4 and IPv6 addresses. IPv4 addresses are 32 bits long, while IPv6 addresses are 128 bits. This function is useful for showing or storing IP addresses in human-readable form.

You call the function with a packed IP address in binary format. It then returns a string representing the address, like '192.168.1.1' for IPv4 or '2001:0db8:85a3:0000:0000:8a2e:0370:7334' for IPv6. If the function fails, it returns False. To handle IPv6 addresses, PHP must include IPv6 functionality.

Syntax

Below is the syntax of the PHP Network inet_ntop() function −

string inet_ntop ( string $ip )

Parameters

This function accepts $ip parameter which is a 32bit IPv4, or 128bit IPv6 address.

Return Value

The inet_ntop() function returns a string representation of the address. And FALSE on failure.

PHP Version

First introduced in core PHP 5.1.0, the inet_ntop() function continues to function easily in PHP 7, and PHP 8.

Example 1

This example shows how to convert a manually packed binary text into a human-readable IPv4 address using the PHP Network inet_ntop() function. The packed binary string \xC0\xA8\x01\x01 denotes the IP address '192.168.1.1'.

<?php
   // Binary representation of an IP Address
   $binary_ip = "\xC0\xA8\x01\x01";  

   // Convert binary IP to readable format
   $readable_ip = inet_ntop($binary_ip);  

   echo $readable_ip;  
?>

Output

Here is the outcome of the following code −

192.168.1.1

Example 2

In this example, an invalid binary string is passed to inet_ntop() which results in a failure. The function returns false, and the program responds with the error message 'Invalid IP address'. This shows error handling when the input is not a valid IP address.

<?php
   // Invalid binary string 
   $invalid_ip = "\xC0\xA8\x01";  

   // Try to convert the invalid address
   $readable_ip = inet_ntop($invalid_ip);  
   if ($readable_ip === false) {
      echo "Invalid IP address"; 
   } else {
      echo $readable_ip;
   }
?> 

Output

This will generate the below output −

Invalid IP address

Example 3

In this code, the inet_ntop() method is used to convert packed binary IP addresses to human-readable text forms. First, it translates the IPv4 address 127.0.0.1 from binary to text. It then translates the IPv6 address::1 from its packed binary form to a readable representation.

<?php
   $packed = chr(127) . chr(0) . chr(0) . chr(1);
   $expanded = inet_ntop($packed);

   echo $expanded;

   $packed = str_repeat(chr(0), 15) . chr(1);
   $expanded = inet_ntop($packed);

   echo $expanded;
?> 

Output

This will create the below output −

127.0.0.1::1
php_function_reference.htm
Advertisements