我可以对 IPv4 地址使用 v 字符串吗?

发布于 2024-10-03 19:55:14 字数 469 浏览 0 评论 0原文

骆驼书建议 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡の花香 2024-10-10 19:55:14

获取编码形式的“标准”方法是 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文