I'm trying to write a Perl script that asks the user to input their IPv4 address and convert it into hexadecimals. For example, if the user enters 130.130.68.1
, it will return 0x82.0x82.0x44.0x01
. How can I do this?
0x82.0x82.0x44.0x01
:
my $hex =
join ".",
map { sprintf "0x%02X", $_ }
split /\./,
$ip;
or
my $hex = $ip =~ s/[^.]+/ sprintf "0x%02X", $& /reg;
That said, 0x82.0x82.0x44.0x01
is a really weird way of writing 8282260116, the 32-bit number 130.130.68.1
represents.
0x82824401
:
use Socket qw( inet_aton );
my $hex = '0x' . unpack('H*', inet_aton('130.130.68.1'));
0x82.82.44.01
:
use Socket qw( inet_aton );
my $hex = '0x' . join('.', unpack('(H2)*', inet_aton('130.130.68.1')));
Both of these also with domain names.