PYTHON ip2long

is this article helpful?
|
Python replacement for PHP's ip2long [ edit | history ]
from socket import inet_aton
from struct import unpack

def ip2long(ip_addr):
    return unpack("!L", inet_aton(ip_addr))[0]

PHP ip2long

PHP original manual for ip2long [ show | php.net ]

ip2long

(PHP 4, PHP 5)

ip2longConverts a string containing an (IPv4) Internet Protocol dotted address into a proper address

Description

int ip2long ( string $ip_address )

The function ip2long() generates an IPv4 Internet network address from its Internet standard format (dotted string) representation.

ip2long() will also work with non-complete IP addresses. Read » http://publibn.boulder.ibm.com/doc_link/en_US/a_doc_lib/libs/commtrf2/inet_addr.htm for more info.

Parameters

ip_address

A standard format address.

Return Values

Returns the IPv4 address or FALSE if ip_address is invalid.

Changelog

Version Description
5.0.0 Prior to this version, ip2long() returned -1 on failure.

Examples

Example #1 ip2long() Example

<?php
$ip 
gethostbyname('www.example.com');
$out "The following URLs are equivalent:<br />\n";
$out .= 'http://www.example.com/, http://' $ip '/, and http://' sprintf("%u"ip2long($ip)) . "/<br />\n";
echo 
$out;
?>

Example #2 Displaying an IP address

This second example shows how to print a converted address with the printf() function in both PHP 4 and PHP 5:

<?php
$ip   
gethostbyname('www.example.com');
$long ip2long($ip);

if (
$long == -|| $long === FALSE) {
    echo 
'Invalid IP, please try again';
} else {
    echo 
$ip   "\n";           // 192.0.34.166
    
echo $long "\n";           // -1073732954
    
printf("%u\n"ip2long($ip)); // 3221234342
}
?>

Example #3 IP validation

ip2long() should not be used as the sole form of IP validation. Combine it with long2ip():

<?php
// make sure IPs are valid. also converts a non-complete IP into
// a proper dotted quad as explained below.
$ip long2ip(ip2long("127.0.0.1")); // "127.0.0.1"
$ip long2ip(ip2long("10.0.0")); // "10.0.0.0"
$ip long2ip(ip2long("10.0.256")); // "10.0.1.0"
?>

Notes

Note: Because PHP's integer type is signed, and many IP addresses will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

Note: ip2long() will return FALSE for the IP 255.255.255.255 in PHP 5 <= 5.0.2. It was fixed in PHP 5.0.3 where it returns -1 (same as PHP 4).

See Also

  • long2ip() - Converts an (IPv4) Internet network address into a string in Internet standard dotted format
  • sprintf() - Return a formatted string