如何将IP地址转换为DWORD?
嘿,如何使用 python 将 ip 地址转换为 DWORD ?
我搜索了一段时间但没有发现任何有用的东西。
感谢各位帮忙的人!
Hey, how can I convert ip address to DWORD using python ?
I searched a while but didn't found anything useful.
Thanks for the helpers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要推出自己的解决方案。使用
socket
库。当它无法正确解析地址时,它会抛出异常,而为事物编写自己的解析器只是解决问题的一个方法。
这样做还可以更轻松地将代码转换到 IPv6。为 IPv6 编写自己的地址解析器将是一个非常糟糕的主意,因为 IPv6 地址很复杂并且有一些奇怪的极端情况。
编辑:显然,这在 Windows 上不起作用。我不确定你应该如何在 Windows 上解析 IPv6 地址,但仍然有一个库调用可以解析 IPv4 地址。它是
socket.inet_aton
,如果socket.inet_pton
不存在,您应该使用它,而不是滚动您自己的解决方案。Don't roll your own solution. Use the
socket
library.It will throw exceptions when it can't properly parse the address, and writing your own parsers for things is just a recipe for problems down the line.
Doing it this way also makes it easier to transition your code to IPv6. And writing your own address parser for IPv6 would be a really bad idea because IPv6 addresses are complex and have some weird corner cases.
Edit: Apparently, this doesn't work on Windows. I'm not sure how you're supposed to parse IPv6 addresses on Windows, but there is still a library call that can parse IPv4 addresses. It's
socket.inet_aton
, and you should use it ifsocket.inet_pton
doesn't exist instead of rolling your own solution.假设您有正确的 IPv4,您可以这样做,例如:
Assuming you have a correct IPv4, you could do this, for example:
Python 没有 DWORD 类型。如果您需要将其作为 4 字节字符串,请使用:
Python doesn't have a DWORD type. If you need it as a 4-byte string use: