Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Pack ipv4 ipv6 to bin

by AlexP (Pilgrim)
on Jul 17, 2022 at 10:04 UTC ( [id://11145558]=perlquestion: print w/replies, xml ) Need Help??

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

Hi monks, i need a script to convert ip's from string representation to bin to save them to my database later.

I came up with something like:

use v5.36; use Carp qw(croak); use Socket qw(AF_INET AF_INET6 inet_ntop inet_pton); use Data::Validate::IP qw(is_ipv4 is_ipv6); my $ip = $ARGV[0]; if (is_ipv4 $ip) { print inet_pton AF_INET, $ip; } elsif (is_ipv6 $ip) { print inet_pton AF_INET6, $ip; } else { croak 'Not a valid ip: ' . $ip; }

I'm interested in is there a shorter and more convenient way to do this in Perl or not?
For example, in php there is inet-pton that could take both ivp4 or ipv6 and do the right thing.

Replies are listed 'Best First'.
Re: Pack ipv4 ipv6 to bin
by Tux (Canon) on Jul 17, 2022 at 11:07 UTC

    Yes, use Net::IP instead.

    #!/pro/bin/perl use 5.018003; use warnings; use Net::IP; use Socket qw(AF_INET AF_INET6 inet_ntop inet_pton); use Data::Validate::IP qw(is_ipv4 is_ipv6); my $ip = $ARGV[0] or die "usage: $0 IP\n"; say "Using Net::IP"; if (my $nip = Net::IP->new ($ip)) { say "IP*"; my $bip = pack "B*" => $nip->binip (); if (length ($bip) == 4) { say join "." => unpack "C*" => inet_pton (AF_INET, $ip); } else { say join ":" => map { sprintf "%04x", $_ } unpack "S>*" => inet_pton (AF_INET6, $ip); } } say ""; say "Using Data::Validate::IP"; if (is_ipv4 ($ip)) { say "IPv4!"; say join "." => unpack "C*" => inet_pton (AF_INET, $ip); } elsif (is_ipv6 ($ip)) { say "IPv6!"; say join ":" => map { sprintf "%04x", $_ } unpack "S>*" => inet_pton (AF_INET6, $ip); } else { die "Not a valid ip: $ip\n"; }

    ->

    $ test.pl 192.168.14.5 Using Net::IP IP* 192.168.14.5 Using Data::Validate::IP IPv4! 192.168.14.5 $ test.pl 0203:3564:a5a5:0001:1234:4321:abcd:fdba Using Net::IP IP* 0203:3564:a5a5:0001:1234:4321:abcd:fdba Using Data::Validate::IP IPv6! 0203:3564:a5a5:0001:1234:4321:abcd:fdba

    Enjoy, Have FUN! H.Merijn

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11145558]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2024-04-26 05:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found