Open In App

PHP | ip2long() Function

Last Updated : 07 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The ip2long() function is an inbuilt function in PHP that converts IPv4 address (dotted IP address) into a long integer.

Syntax: 

int ip2long( string $ip_address )

Parameters: This function accepts single parameter as mentioned above and described below:  

  • $ip_address: It is required parameter which specifies an IP address.

Return Value: This function returns a long integer on success or FALSE on failure.

Note:  

  • This function is available on PHP 4.0.0 and newer versions.
  • This function will work with non-complete IP addresses.

Below programs illustrate the ip2long() function in PHP:

Program 1:  

PHP




<?php
 
// Store host name into variable
$host="geeksforgeeks.org";
 
// Get IP address from hostname
$ip = gethostbyname($host);
 
echo "These three URLs are equivalent:<br>";
 
$out = "1. https://" . $host . "/<br>" .
       "2. https://" . $ip . "/<br>" .
       "3. https://" . sprintf("%u", ip2long($ip)) . "/";
 
echo $out;
 
?>


Output: 

These three URLs are equivalent:
1. https://geeksforgeeks.org/
2. https://52.25.109.230/
3. https://874081766/

Program 2:  

PHP




<?php
 
// Store the list of hostname in an array
$hosts = array(
    "geeksforgeeks.org",
    "www.google.com",
    "www.youtube.com",
    "www.facebook.com",
    "www.quora.com",
    "www.stackoverflow.com"
);
 
$out = "Equivalent Contents:";
 
foreach( $hosts as $host ) {
     
    $ip = gethostbyname($host);
     
    $out .= "<br>https://" . $host . "/  https://" . $ip .
            "/  https://" . sprintf("%u", ip2long($ip)) . "/";
}
 
echo $out;
 
?>


Output: 

Equivalent Contents:
https://geeksforgeeks.org/ https://52.25.109.230/ https://874081766/
https://www.google.com/ https://172.217.167.196/ https://2899945412/
https://www.youtube.com/ https://172.217.18.206/ https://2899907278/
https://www.facebook.com/ https://185.60.216.35/ https://3107772451/
https://www.quora.com/ https://151.101.1.2/ https://2539979010/
https://www.stackoverflow.com/ https://151.101.1.69/ https://2539979077/

Reference: https://www.php.net/manual/en/function.ip2long.php
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads