2011-09-23 10 views
7

Sto tentando di utilizzare libpcap in python3 utilizzando ctypes.ctypes e passaggio di un riferimento a una funzione

data la seguente funzione in C

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

in python ho il seguente

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) 

e l'errore che ottengo è

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 

come si fa a trattare con & bla valori ?

risposta

13

È necessario creare istanze per net e mask e utilizzare byref per passarle.

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

Stackoverflow dice di evitare l'uso di commenti come "grazie", ma ho impiegato molto tempo a cercare di trovare una soluzione a questo problema. Quindi grazie! :) – LuckyLuc

1

probabilmente è necessario utilizzare ctypes.pointer, in questo modo:

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

Vedi le ctypes sezione tutorial su pointers per ulteriori informazioni.

Sto assumendo che hai creato ctypes deleghe per gli altri argomenti pure. Se dev richiede una stringa, ad esempio, non puoi semplicemente passare una stringa Python; devi creare uno ctypes_wchar_p o qualcosa del genere.

+0

rete e la maschera sono tipi molto specifici, vedi sotto int pcap_lookupnet (const char * dispositivo, bpf_u_int32 * NETP, bpf_u_int32 * maskp, char * errbuf); – user961346

+0

bpf_u_int32 è davvero solo ... typedef u_int bpf_u_int32; – user961346

1

ctypes.c_uint32 è un tipo. Avete bisogno di un esempio:

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

quindi passare con ctypes.byref:

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

è possibile recuperare il valore con mask.value.