« Requiem for a 1st Generation iPod | Main | Note To Self... »

July 20, 2005

perl version of ip2long() and long2ip()

In order to save the sanity of anyone else that might wonder about how to convert an IP address into a signed integer in perl (accounting for endianness as well):
#!/usr/bin/perl
use warnings;
use strict;
use Socket;

if ($ARGV[0] =~ /\d+\.\d+\.\d+\.\d+/) {
    my $ip_address = shift(@ARGV);
    my $ip_number = ip2long($ip_address);
    print "$ip_address converts to $ip_number\n";
} else {
    my $ip_number = shift(@ARGV);
    my $ip = long2ip($ip_number);
    print "$ip_number converts to $ip\n";
}

sub ip2long {
    return unpack("l*", pack("l*", unpack("N*", inet_aton(shift))));
}

sub long2ip {
    return inet_ntoa(pack("N*", shift));
}

Posted by ed at July 20, 2005 6:23 PM

Comments

This is really smart, but what this doing for you?:
unpack("l*",pack("l*",$foo))

Posted by: krets at November 30, 2005 2:51 PM

je bent een sprintf("%u",...) vergeten

Posted by: ik at December 19, 2005 9:40 AM

Acording to Babelfish the last commenter said I forgot about sprintf("%u", ...)

You are right, I had forgotten that. Thanks.

Posted by: Ed at December 19, 2005 4:28 PM

dude, you have no idea how much better you just made my life. i still don't know why inet_aton and inet_ntoa from Socket won't convert IPs like the mysql functions by the same (uppercased) names, so I was going through all kinds of hoops trying to make the conversion happen on the database side.

anyway, thanks.

Posted by: Neal at January 7, 2007 9:00 PM

Post a comment




Type the characters you see in the picture above.


Remember Me?