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!
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!
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])
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('.')))
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.