views:

156

answers:

2

I am building peer to peer application in python. Its going to work over UDP. I have function called getHeader(packetNo,totalPackets) which returns me the header for that packet.Depending on size of header I am chopping data, attaching data to header and getting same packet size.

Header size is not fixed because length consumed by different no of digits is different e.g. I am writing header for packetNo=1 as PACKET_NO=1 , its length will be different for packetNo 10, 100,.. etc

I am currently not including no of packets in header. I am just including packet number, I want to include it, but how can I know no of packets prior to computing header size as header should now contain no of packets and NO_OF_PACKETS=--- can be of any length.

I can pass it through some function which will compute no of packets but that will be something like brute force and will consume unnecessary time and processing power. Is there any intelligent way to do it?

+2  A: 

Don't use plain-text. Make packet's header a two packed 4-byte (or 8-byte, depending on how many packets you expect) integers, e.g.

import struct
header = struct.pack('!II', packetNo, totalPackets)

Here's documentation for struct module.

PiotrLegnica
but that will put limit on no of packets ..
Xinus
Yes, 64-bit unsigned integer will limit number of packets to 2^64, 32-bit to 2^32. Use a bigger one if you're really concerned with that limit (e.g. two 64-bit uints for packetNo and two for totalPackets; that would give you the limit of 2^128).
PiotrLegnica
You will not need more than a 64 bit value. Even if you send a million packets per second, the packet number will take more than half a million years to wrap around. By then we'll all be long dead, so it'll be well and truly someone else's problem. Guess they'll have to restart the connection ;)
caf
A: 

Why not zero-pad your number of packets, so that the header becomes fixed. Say you want to support 1 billion packets in a message:

PACKET_NO=0000000001

is the same length as:

PACKET_NO=1000000000

Of course, this will create an upper bound on the possible number of packets, but there has to be some upper limit, no?

Paul McGuire