views:

471

answers:

3

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!

A: 

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])
AndiDog
A: 

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('.')))
Ignacio Vazquez-Abrams
And if the endian-ness is out of whack, would you do reverse('127.0.0.1'.split('.')) ?
Hamish Grubijan
No, I'd just use `[::-1]` on the resultant string.
Ignacio Vazquez-Abrams
I would make `struct` handle the endianness issues.
Omnifarious
After thinking about this, I'm going to have to vote you down. Writing your own parsers when the library has a perfectly good parser is a bad idea.
Omnifarious
+3  A: 

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.

Omnifarious