2011-09-23 37 views
7

我想在python3中使用libpcap使用ctypes。ctypes和通過引用功能

給C中的以下功能

pcap_lookupnet(dev, &net, &mask, errbuf) 

在python,我有以下

pcap_lookupnet = pcap.pcap_lookupnet 

mask = ctypes.c_uint32 
net = ctypes.c_int32 

if(pcap_lookupnet(dev,net,mask,errbuf) == -1): 
print("Error could not get netmask for device {0}".format(errbuf)) 
sys.exit(0) 

和我得到的錯誤是

File "./libpcap.py", line 63, in <module> 
if(pcap_lookupnet(dev,net,mask,errbuf) == -1): 
ctypes.ArgumentError: argument 2: <class 'TypeError'>: Don't know how to convert parameter 2 

你如何處理與&嗒嗒值?

回答

13

您需要爲netmask創建實例,並使用byref來傳遞它們。

mask = ctypes.c_uint32() 
net = ctypes.c_int32() 
pcap_lookupnet(dev, ctypes.byref(net), ctypes.byref(mask), errbuf) 
+0

Stackoverflow說爲了避免使用像「謝謝」這樣的評論,但我花了很長時間試圖找出解決這個問題的方法。所以謝謝! :) – LuckyLuc

1

您可能需要使用ctypes.pointer,像這樣:

pcap_lookupnet(dev, ctypes.pointer(net), ctypes.pointer(mask), errbuf) 

見ctypes的上pointers教程部分獲取更多信息。

我假設你已經爲其他參數創建了ctypes代理。例如,如果dev需要一個字符串,則不能簡單地傳入一個Python字符串;您需要創建一個ctypes_wchar_p或沿着這些線路。

+0

淨和掩模真的特定類型見下文INT pcap_lookupnet(常量字符*設備,bpf_u_int32 * NETP, bpf_u_int32 * maskp,字符* errbuf); – user961346

+0

bpf_u_int32真的只是... typedef u_int bpf_u_int32; – user961346

1

ctypes.c_uint32類型。你需要一個實例:

mask = ctypes.c_uint32() 
net = ctypes.c_int32() 

然後通過使用ctypes.byref

pcap_lookupnet(dev,ctypes.byref(mask),ctypes.byref(net),errbuf) 

您可以檢索使用mask.value值。