i have c++ code generates ip packet header. code use struct representing each field in packet:
struct cip { uint8_t ip_hl:4, /* both fields 4 bytes */ ip_v:4; uint8_t ip_tos; uint16_t ip_len; uint16_t ip_id; uint16_t ip_off; uint8_t ip_ttl; uint8_t ip_p; uint16_t ip_sum; struct in_addr ip_src; struct in_addr ip_dst; char head[100]; };
the user prompt input message enter values each variable in struct:
enter filename save packet: packet
enter ip version(0-15): 4
enter header length(5-15): 5
enter type of service(0-255): 55
enter packet total size(bytes, 20, 200): 25
the packet created , saved in file:
file* f = fopen(file, "w"); int success = fwrite(&packet, sizeof(char), ((unsigned int)packet.ip_hl)*4,f); if(success <= 0) { printf("error writing packet header"); } success = fwrite(&data, sizeof(char),ntohs(packet.ip_len)-(4*packet.ip_hl),f); if(success < 0) { printf("error writing packet data"); } fflush(f); fclose(f); printf("\npacket written.\n");
i didn't create code, gave me code can create other program in python validate packet created program above. validation includes verifying checksum generated packet, version of ip packet, protocol, length of header , on.
so know if can me figuring out how can read file , parse frame. tried read line in file string, problem i'm having file looks after creation: (it unreadable)
o È ,@ šÀ¨À¨ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdata_______________________data____________ ô·
i don't understand why: (i'm guessing because variables bigger 1 byte converted big endian function "htons":
printf("\nenter ip id number(0-65535):\n"); scanf("%d", &input); packet.ip_id = htons(input);
i tried search option dealing socket.makefile(), me socket in program file, need parse frame gave me in file.
any ideas?
thanks.
p.s.: can give me link can find how convert integer big endian small endian , vicerversa in python. thanks!
you should read file usual (specifying "binary" mode windows):
with open("test.txt", 'br') f: line in f.readlines(): # process lines
to unpack binary data should use struct
package, can handle big , little endian , on. example struct:
print struct.unpack('bbhhhbbh100s', line)
i omitted ip_src
, ip_dst
unpacking since didn't specify contents of struct. least possible value read 1 byte, split first field 2 parts can use:
(ip_hl, ip_v) = (value >> 4, value & 15)
of course, order of 8-bit component depends on struct endianess.
Comments
Post a Comment