Writing UDP Packet body

Feb 16, 2012 at 3:38am
Hey guys, I am new to network programming and I am trying to send a custom packet across a network using UDP. I can send and receive just fine (I 'cin' into a char buffer, send that to the server, it receives it and prints it out). I understand what I need to do to create a packet that needs to be sent across a network, but I dont know how to go about it..

From what I know:

I have a PacketHeader class of a set size, it contains 3 ints: Packet type, packet size, packet segment. I have another object, a 'Packet'. Packet contains a Packet Header object, (12 bytes) and up to 500 bytes of 'data'. Now I can't get my head around how to 'write' up to 500 bytes of data.

Lets say I have an int. 4 bytes of data. Easy! How do I 'write' it into my 'data' object. And firstly, what IS the 'data' object? A char buffer (length of 500) ? How do i write data in to this buffer?


now when the data arrives at the other side, I would have to read into the first 12 bytes to see what type of file this is (Packet type), its size and segment number. This would be accomplished by casting the first 4 bytes of the pointer to an int..somehow. incrementing the pointer by 4, and so on until i read the first 3 ints. I would then know enough to cast the remaining 500 bytes (Or however many is specified in the packet header 'packet size').


I just can't get my head around these 'low level' details.. I just understand how its supposed to work, not its implementation..
Feb 16, 2012 at 2:25pm
If you want to write 4 bytes of data, you need to create a buffer that has a packet header followed by 4 bytes. PacketHeader must be byte aligned, so the size will be 12 bytes (three 32bit numbers). So the buffer size must be 16 bytes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int write(const PacketHeader &hdr, char* data, size_t datasize)
{
    size_t buffer_size = sizeof(PacketHeader) + datasize;
    char* buffer = new char[buffer_size];

    // copy over the packet details
    PacketHeader* bufhdr = reinterpret_cast<PacketHeader*>(buffer)
    *bufhdr = hdr;
    bufhdr->pkt-size = datasize;

    // copy over the data
    memcpy(buffer + sizeof(PacketHeader), data, datasize);

    // write the packet
    int ret = sendto(s, buffer, buffer_size, 0, dst, dst_size);

    // ... 

Topic archived. No new replies allowed.