mosh has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm trying to convert ip address: 1.1.1.9 to 01 01 01 09.
How do I convert it with the assistance of PACK command ?
I tried to do it with 'H8':

$new = pack ('ncH8n',$x, $y, $ip, $z)

What I got in the ip section is: 11 19 00 00

Any ideas ?

Mosh.

Replies are listed 'Best First'.
Re: Pack command
by Limbic~Region (Chancellor) on Apr 18, 2005 at 13:51 UTC
    mosh,
    I am going to forget for a second you said IP address and that you want to use pack.
    my $new = join '', map { sprintf('%.2d', $_) } split /\./, $ip;
    If you really want the spaces just change the first argument to join. I am not great at pack/unpack so I use what I know works. I question what you would want to happen if you have 3 digit octets?

    Cheers - L~R

      I found the answer !!
      it is 'a4'
      Thanks anyway.
      Mosh.
Re: Pack command
by BrowserUk (Patriarch) on Apr 18, 2005 at 14:15 UTC

    Presumably, you want to pack the four octets of the IP as chars in the output string? (Your use of '01 01 01 09' to indicate this is quite confusing--looking more like you want the ascii-ized value padded with leading zeros!).

    Assuming that the var $ip contains the ip in it's ascii form (with '.' delimiters) the answer is "No, not directly". You will need to break the IP up into it numeric components before passing it to pack:

    $new = pack 'ncC4n', 10, 10, split( '\.', '1.1.1.9' ), 30; print unpack 'C*', $new; 0 10 10 1 1 1 9 0 30

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco.
    Rule 1 has a caveat! -- Who broke the cabal?
Re: Pack command
by tlm (Prior) on Apr 19, 2005 at 03:15 UTC

    I say unto you the words of Stein The Wise:

    ($a,$b,$c,$d) = split /\./, '18.157.0.125'; $packed_ip_address = pack 'C4', $a, $b, $c, $d; ($a,$b,$c,$d) = unpack 'C4',$packed_ip_address; $dotted_ip_address = join '.', $a,$b,$c,$d;
    Transcribed reverently from page 69 of Network Programming with Perl, a very worthy tome.

    the lowliest monk