Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Converting an IP from hexadecimal to dotted-quad

by cpc (Hermit)
on Aug 29, 2002 at 03:01 UTC ( [id://193651]=perlquestion: print w/replies, xml ) Need Help??

cpc has asked for the wisdom of the Perl Monks concerning the following question: (data formatting)

What would be the most efficient way to convert an IP address from hexadecimal to dotted quad notation?
E.g. from 7F000001 to 127.0.0.1

I came up with:

$ip = '7F000001'; use Socket; inet_ntoa( pack( "N", hex( $ip ) ) )

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Converting an IP from hexadecimal to dotted-quad
by merlyn (Sage) on Aug 29, 2002 at 04:26 UTC
    perhaps
    join '.', unpack "C*", pack "H*", $ip;
Re: Converting an IP from hexadecimal to dotted-quad
by Abigail-II (Bishop) on Aug 29, 2002 at 13:28 UTC
    Here's one way, using Regexp::Common, although it's unlikely to be the most efficient:
    use Regexp::Common; $ip =~ s( ^$RE{net}{IPv4}{hex}{-sep=>''}{-keep}$ ){ join '.', map { hex } $2, $3, $4, $5 }xe;
Re: Converting an IP from hexadecimal to dotted-quad
by jmcnamara (Monsignor) on Aug 29, 2002 at 08:24 UTC
    You could also do it as follows, although it's still probably not as fast as the pack/unpack method:
    join '.', map { hex } $ip =~ /../g;
Re: Converting an IP format from 7F000001 to 127.0.0.1
by cpc (Hermit) on Aug 29, 2002 at 07:05 UTC
    Definitely nicer to use the pack/unpack/join combo.
    Thanks

    Originally posted as a Categorized Answer.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (8)
As of 2024-04-24 12:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found