如何将IP地址转换为DWORD?

发布于 2024-08-20 22:50:57 字数 87 浏览 3 评论 0原文

嘿,如何使用 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 技术交流群。

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

发布评论

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

评论(3

喜你已久 2024-08-27 22:50:57

不要推出自己的解决方案。使用socket 库。

import socket
socket.inet_pton(socket.AF_INET, "127.0.0.1")

当它无法正确解析地址时,它会抛出异常,而为事物编写自己的解析器只是解决问题的一个方法。

这样做还可以更轻松地将代码转换到 IPv6。为 IPv6 编写自己的地址解析器将是一个非常糟糕的主意,因为 IPv6 地址很复杂并且有一些奇怪的极端情况。

编辑:显然,这在 Windows 上不起作用。我不确定你应该如何在 Windows 上解析 IPv6 地址,但仍然有一个库调用可以解析 IPv4 地址。它是 socket.inet_aton,如果 socket.inet_pton 不存在,您应该使用它,而不是滚动您自己的解决方案。

Don't roll your own solution. Use the socket library.

import socket
socket.inet_pton(socket.AF_INET, "127.0.0.1")

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 if socket.inet_pton doesn't exist instead of rolling your own solution.

耶耶耶 2024-08-27 22:50:57

假设您有正确的 IPv4,您可以这样做,例如:

import struct

ip = "192.168.2.101"
components = map(int, ip.split("."))
asLittleEndianDword = struct.pack("<I", (components[0] << 24) |
                                        (components[1] << 16) |
                                        (components[2] << 8) |
                                        components[3])

Assuming you have a correct IPv4, you could do this, for example:

import struct

ip = "192.168.2.101"
components = map(int, ip.split("."))
asLittleEndianDword = struct.pack("<I", (components[0] << 24) |
                                        (components[1] << 16) |
                                        (components[2] << 8) |
                                        components[3])
扛起拖把扫天下 2024-08-27 22:50:57

Python 没有 DWORD 类型。如果您需要将其作为 4 字节字符串,请使用:

struct.pack('bbbb', *(int(x) for x in '127.0.0.1'.split('.')))

Python doesn't have a DWORD type. If you need it as a 4-byte string use:

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