Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help w/pack 2

Status
Not open for further replies.

bardley

Programmer
May 8, 2001
121
US
I still can't grasp how the pack function works.

I need to turn dotted ip addresses to decimal representations like so:

10.50.1.5 (the ip address)
0a.32.01.05 (change each octet to hex)
0a320105 (concatenate the octets)
171049221 (change that hex number back to decimal)

I just know there's a cool way to do this using pack, but I haven't been able to get it. It may even be in a module, I just haven't looked in the right place.

Brad Gunsalus
Cymtec Systems, Inc.
bgunsalus@cymtec.com
 
Not using pack, but this gives you the steps you want:
Code:
$ip = "10.50.1.5";
$ip =~ s/(\d+)/sprintf("%02x",$1)/eg;
print "$ip\n";
$ip =~ s/\.//g;
print "$ip\n";
$ip = hex( $ip );
print "$ip\n";
Cheers, Neil :)
 
This is a little nasty but it works in one line:

my $out = hex(join('', map(sprintf("%02x", $_), split( /\./, $ip))));

The join uses two single quotes, not one double quote.
 
nasty is right, neat though Mike
"Experience is the comb that Nature gives us after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
And the same thing using pack:
Code:
$ip = unpack( "N", pack( "C4", ( split( /\./, $ip ) ) ) );
Reading from the inner brackets out:
[tt]split( /\./, $ip )[/tt] returns an array of 4 integers
[tt]pack( "C4", ... )[/tt] packs these as 4 signed chars
[tt]unpack( "N", ... )[/tt] unpacks the data as a single big-endian long (4 bytes).
Cheers, Neil

 
I knew if I threw it out there, I'd end up with at least one one-liner, and probably more. :)

Awesome, thanks guys! Brad Gunsalus
Cymtec Systems, Inc.
bgunsalus@cymtec.com
 
A two-liner:
Code:
use Socket;
$ip = unpack( "N", inet_aton( $ip ) );
This will also accept an initial string like
Code:
"www.tek-tips.com"
. Try [tt]perldoc Socket[/tt] for more information on the functions that are available with this package.

Cheers, Neil :)
 
Spot on Neil :) I'll use that. Mike
"Experience is the comb that Nature gives us after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top