Preparing a UDP packet with SDL_net

I’m trying to write a client/server MMO using SDL_net for the networking on
both sides. However, I’ve run into a problem when using the SDLNet_WriteXX
family of functions. I’m trying to write a 16-bit packet type ID to a UDP
packet, but it always segfaults.

This is the code that I create my packets with:
// initialize packet to given size
packet = SDLNet_AllocPacket(buffer_size + 1);
if (!packet) {
cout << “[error] failed to create packet” << endl;
return;
}
// zero out the packet
memset(packet->data, 0, buffer_size + 1);

And this is the code I use for writing data to the packet:
void AO_Packet::write16(Uint16 src) {
if (read_only) return;
if (position + sizeof(src) > packet->maxlen) {
string error = “write16: not enough room in packet”;
cout << "[debug] " << error << endl;
return;
}
SDLNet_Write16(src, packet->data[position]);
position += sizeof(src);
}

Whenever my code runs, however, I get a segfault the first time
SDLNet_Write16 is called. The packet was successfully created, though, and
position is set to 0. Now I can’t figure out what I’m doing wrong.–
“If you see somebody who you don’t know getting into a crop duster that
doesn’t belong to you, report them.” – President George W. Bush

James Buchwald wrote:

SDLNet_Write16(src, packet->data[position]);

I think this should be:

SDLNet_Write16(src, (char *)packet->data + position);

The cast may not be needed if packet->data is already a pointer to an
8bit sized type.

Whenever my code runs, however, I get a segfault the first time
SDLNet_Write16 is called. The packet was successfully created, though,
and position is set to 0. Now I can’t figure out what I’m doing wrong.
You were writing to the memory address 0 (data[x] was zeroed for every x
:slight_smile: )

Bye,
Gabry

Someone already emailed me a solution that works:

SDLNet_Write16(src, &packet->data[position]);

It looks to me like your solution is just another way of writing the
above… Thanks anyway, though.On 6/22/07, Gabriele Greco <gabriele.greco at darts.it> wrote:

James Buchwald wrote:

SDLNet_Write16(src, packet->data[position]);

I think this should be:

SDLNet_Write16(src, (char *)packet->data + position);

The cast may not be needed if packet->data is already a pointer to an
8bit sized type.

Whenever my code runs, however, I get a segfault the first time
SDLNet_Write16 is called. The packet was successfully created, though,
and position is set to 0. Now I can’t figure out what I’m doing wrong.
You were writing to the memory address 0 (data[x] was zeroed for every x
:slight_smile: )

Bye,
Gabry


SDL mailing list
SDL at lists.libsdl.org
http://lists.libsdl.org/listinfo.cgi/sdl-libsdl.org


“If you see somebody who you don’t know getting into a crop duster that
doesn’t belong to you, report them.” – President George W. Bush