dimanche 1 mars 2015

C / Python WinPCap Translation



Sorry, this will be a very simple question for most of you.


I'm trying to convert some of the code from here into Python (3.4) as I don't know C. That's primarily the basis of this issue. While I have created the Python data structures according to the link:



from ctypes import *
u_short = c_ushort
u_char = c_ubyte
u_int = c_int

class ip_address(Structure):
_fields=[("byte1",u_char),
("byte2",u_char),
("byte3",u_char),
("byte4",u_char)]

class ip_header(Structure):
_fields=[("ver_ihl",u_char),
("tos",u_char),
("tlen",u_short),
("identification",u_short),
("flags_fo",u_short),
("ttl",u_char),
("proto",u_char),
("crc",u_short),
("saddr",ip_address),
("daddr",ip_address),
("op_pad",u_int)]

class udp_header(Structure):
_fields=[("sport",u_short),
("dport",u_short),
("len",u_short),
("crc",u_short)]

class data(Structure):
_fields[("data",c_char_p)]


I don't know enough about C to convert the following code in Python:



ip_header *ih;
udp_header *uh;
u_int ip_len;
u_short sport,dport;

/* retrieve the position of the ip header */
ih = (ip_header *) (pkt_data +
14); //length of ethernet header

/* retrieve the position of the udp header */
ip_len = (ih->ver_ihl & 0xf) * 4;
uh = (udp_header *) ((u_char*)ih + ip_len);

/* convert from network byte order to host byte order */
sport = ntohs( uh->sport );
dport = ntohs( uh->dport );

/* print ip addresses and udp ports */
printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",
ih->saddr.byte1,
ih->saddr.byte2,
ih->saddr.byte3,
ih->saddr.byte4,
sport,
ih->daddr.byte1,
ih->daddr.byte2,
ih->daddr.byte3,
ih->daddr.byte4,
dport);


I know that I need to change the "ih->ver_ihl" to "ih.ver_ihl" however I don't understand the rest. If I understand UDP packets correctly, the next section of the packet will be Data. I would also like to extract that from the packet if possible.


Thanks in advance for any help you can provide




Aucun commentaire:

Enregistrer un commentaire