Reputation: 67
I'm trying to write a perl script that asks user to input their ipv4 address and convert it into hexadecimals. For example, user enters "130.130.68.1" which will return "0x82.0x82.0x44.0x01". How can i do this?
Upvotes: 3
Views: 689
Reputation: 386561
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.
Upvotes: 4