Can I use v-strings for IPv4 addresses?
The camel book suggests that V-strings can be used for representing IPv4 addresses:
$ipaddr = 204.148.40.9; # the IPv4 address of oreilly.com
But perldata on the topic of Version Strings states:
Note that using the v-strings for IPv4 addresses is not portable unless you also use the inet_aton()/inet_ntoa() routines of the Socket package.
I have two 开发者_开发技巧questions:
1) Why is using the v-strings not portable?
2) What's the "standard" way to convert an ip-address from dotted notation to integer? Seems thatunpack "N", <v-string>
can cause problems sometimes.The "standard" way to get the encoded form is inet_aton
, which handles dotted IP addresses as well as hostnames -- but what do you need it for? More often than not the best idea is just to skip all of the low-level interfaces that deal with such things and use, e.g., IO::Socket.
If you're looking to convert to integer, as you say, and not to the form that socket functions expect (they're similar concepts in C, but less so in Perl), then you can go ahead and use pack
just fine as long as you're consistent -- the part that's unportable is the format that socket functions accept. For example, unpack "N", pack "C4", split /\./, "1.2.3.4"
will get you a nice unsigned big-endian representation of that address (in the form of the number 16909060 == 0x01020304
).
精彩评论