Python: packing an ip address like ctype.c_ulong () for use with a DLL

given the following code:

import ctypes    
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)

how can I package this correctly for a DLL that expects it as a c_ulong data type?

I tried using:

ip_netFrmt = socket.inet_aton(ip)
ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt)

however, the method c_ulong()returns an error because it requires an integer.

Is there a way to use struct.packto accomplish this?

+3
source share
4 answers

Inet_aton returns a string of bytes. This used to be the lingua franca language for C interfaces.

Here's how to unpack these bytes into a more useful value.

>>> import socket
>>> packed_n= socket.inet_aton("128.0.0.1")
>>> import struct
>>> struct.unpack( "!L", packed_n )
(2147483649L,)
>>> hex(_[0])
'0x80000001L'

This unpacked value can be used with ctypes. The hexagonal thing is just to show you that the unpacked value is like an IP address.

+6

-, : .

ip- - xxx.xxx.xxx.xxx, . 192.168.1.1 uniged int. .

ip="192.168.1.1"
ip_long = reduce(lambda x,y:x*256+int(y), ip.split('.'), 0)
0

Probably the best way, but this works:

>>> ip = "192.168.1.1"
>>> struct.unpack('>I', struct.pack('BBBB', *map(int, ip.split('.'))))[0]
3232235777L
0
source

For a more thorough way of handling IP addresses (v6, CIDR-style stuff, etc.) check how this is done in py-radix , especially prefix_pton .

0
source

All Articles