简体   繁体   English

Python:将ip地址打包为ctype.c_ulong()以与DLL一起使用

[英]Python: packing an ip address as a ctype.c_ulong() for use with DLL

given the following code: 给出以下代码:

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

how can I correctly pack this for a DLL that expects it as a c_ulong datatype? 我怎样才能正确地将其打包为期望它作为c_ulong数据类型的DLL?

I've tried using: 我尝试过使用:

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

however, the c_ulong() method returns an error because it needs an integer. 但是, c_ulong()方法返回错误,因为它需要一个整数。

is there a way to use struct.pack to accomplish this? 有没有办法使用struct.pack来实现这一目标?

The inet_aton returns a string of bytes. inet_aton返回一个字节字符串。 This used to be the lingua franca for C-language interfaces. 这曾经是C语言界面的通用语言

Here's how to unpack those 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. 这个解压缩的值可以与ctypes一起使用。 The hex thing is just to show you that the unpacked value looks a lot like an IP address. hex函数只是为了向您展示解压缩的值看起来很像IP地址。

First a disclaimer: This is just an educated guess. 首先是免责声明:这只是一个有根据的猜测。

an ip-address is traditionally represented as four bytes - ie xxx.xxx.xxx.xxx, but is really a unsigned long. ip-address传统上表示为四个字节 - 即xxx.xxx.xxx.xxx,但实际上是无符号长整数。 So you should convert the representation 192.168.1.1 to an unsiged int. 所以你应该将表示192.168.1.1转换为unsiged int。 you could convert it like this. 你可以像这样转换它。

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

There's probably a better way, but this works: 可能有更好的方法,但这有效:

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

For a more thorough way of handling IPs (v6, CIDR-style stuff etc) check out how it's done in py-radix , esp. 有关处理IP的更全面的方法(v6,CIDR风格的东西等),请查看它是如何在py-radix中完成的 ,尤其是。 prefix_pton . prefix_pton

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM