[gameprogrammer] Re: problem filling a buffer

ons, 21 03 2007 kl. 14:15 -0500, skrev Roger D Vargas:
> I have a problem with the udp packet data creation. I still dont deeply 
> underestand pointers, and I need to fill the data buffer with several 
> different data, like this:
> command, user login string length, login string, password string length, 
> password string
> For simple data types like integers I have a working method. But when I 
> send strings I receive some extra garbage at the end, making the login 
> process fail.
> I would appreciate any suggestion to deal with this problem
Hi Roger

I have been programming C/C++ for the past ~10 years and still i
sometimes screw up my pointers, i don't think any programmer can say he
has reached a point where he doesn't make the occasional screw up.

One thing that could ease filling a buffer i to just use a structure to
hold your data, and then pass a pointer to that as the buffer, e.g.:

static const int COMMAND_LOGIN = 20;
static const int MAX_STRING = 10;
typedef struct {
        int command;
        char username[MAX_STRING];
        char password[MAX_STRING];
} Login;

/* And for sending: */
void send_login ( char *username, char *password ) {
    Login login;
    SDLNet_Write32 ( COMMAND_LOGIN, &login.command );
    strncpy ( login.username, username, MAX_STRING );
    strncpy ( login.password, password, MAX_STRING );
    login.username[MAX_STRING - 1] = '\0';
    login.password[MAX_STRING - 1] = '\0';
    UDP_send ( socket, &login, sizeof(Login) );
}

The only bad thing about this is that the username and password strings
becomes restricted to MAX_STRING characters.

A few other notes:

When sending an integer it is normal to transmit it in "network order"
to assure the same order of bytes in an integer across different
processor architectures. When unwrapping you can just use SDLNet_Read32
to read from network-order to the users architecture.

Also note that the last character of strings are always set to null to
make sure that the strings are terminated - this is probably where your
"garbage" characters comes from.

Of course, if you are writing C++ you could wrap all this horrible code
inside a class - the memory layout of the data will be the exact same.

P.S. This is just off-my-head code, no compilers or libraries where
involved (i've never used the UDP part of SDL_net).

Hope it helps, follow-up questions are welcome.

-- 
Rasmus Toftdahl Olesen <halfdan@xxxxxxxxxxxx>
halfdans.net


---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: