我可以对 IPv4 地址使用 v 字符串吗?
骆驼书建议 V 字符串可用于表示 IPv4 地址:
$ipaddr = 204.148.40.9; # the IPv4 address of oreilly.com
但是关于该主题的 perldata版本字符串指出:
请注意,对 IPv4 使用 v 字符串 地址不可移植,除非您 还可以使用 inet_aton()/inet_ntoa() Socket 包的例程。
我有两个问题:
1)为什么使用 v 弦不可移植?
2)将IP地址从点分符号转换为整数的“标准”方法是什么?似乎 unpack "N",
有时会导致问题。
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 that unpack "N", <v-string>
can cause problems sometimes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
获取编码形式的“标准”方法是
inet_aton
,它可以处理点分 IP 地址和主机名 - 但您需要它做什么?通常,最好的想法就是跳过处理此类事情的所有低级接口并使用例如 IO::Socket。如果您希望转换为整数,正如您所说,而不是套接字函数期望的形式(它们在 C 中是类似的概念,但在 Perl 中则不然),那么您可以只要保持一致,就可以提前使用
pack
即可 - 不可移植的部分是套接字函数接受的格式。例如,unpack "N", pack "C4", split /\./, "1.2.3.4"
将为您提供该地址的一个很好的无符号大端表示(以号码 16909060 ==0x01020304
)。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
).