PHP | ip2long() Function

The ip2long() function is an inbuilt function in PHP which 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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;
  
?>

chevron_right


Output:

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

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Store the list of hostname in an arry
$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;
  
?>

chevron_right


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



My Personal Notes arrow_drop_up

I am unrecognized crazy being with random thoughts

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.