Parsing data from winsock

Started by
2 comments, last by Oobydoobyscoobydo 15 years, 8 months ago
I'm trying to get some data from winsock. The data is held in a buffer of type char*, and I also know the amount of data which is stored in an int. how do i get from char* to the actual data in the buffer ?
Advertisement
Depends on how you encoded the data before you sent it. If you just sent a struct over the link, you can just cast the char* pointer to a pointer to some_struct*. Beware of doing this though, since that kind of setup is prone to problems regarding struct padding, byte ordering and just about any other platform, version or compiler incompatibility you can imagine.
Here's a portion of my Disassemble function, maybe it will help you. I encode my packets with a specific format. c h d f s, depending upon what kind of data i'm sending.

const unsigned char *Disassemble(const unsigned char* packet, const char* format, ...){const char* f = format;va_list ap;int t;va_start(ap, format);while ((t = *format++)){switch (t){case 'c':{char* cp = va_arg(ap, char*);*cp = *packet++;}break;case 'h':{short* hp = va_arg(ap, short*);#ifdef _WIN32*hp = ((short *)packet)[0];#else*hp = packet[0] + (packet[1] << 8);#endifpacket += 2;}break;case 'd':{int* dp = va_arg(ap, int*);#ifdef _WIN32           // CPU specific optimization.*dp = ((int *)packet)[0];#else*dp = packet[0] + (packet[1] << 8) + (packet[2] << 16) + (packet[3] << 24);#endifpacket += 4;}break;case 'f':{double* dp = va_arg(ap, double*);#ifdef _WIN32           // CPU specific optimization.CopyMemory(dp, packet, 8);#else*dp = packet[0] + (packet[1] << 8) + (packet[2] << 16) + (packet[3] << 24)+ (packet[4] << 32) + (packet[5] << 40) + (packet[6] << 48) + (packet[7] <<56> dstLen) {//          //Add log}packet = end;}break;case 'S':{int len = va_arg(ap, int) / sizeof(wchar_t);len = WcsNLen(packet, len-1);wchar_t* dst = va_arg(ap, wchar_t*);memcpy(dst, packet, len * sizeof(wchar_t));dst[len] = 0;packet += (len + 1) * sizeof(wchar_t);}break;default://Add log}}va_end(ap);return packet;}


Edit: While copying and pasting I guess I lost all the whitespace so the code looks a little bit messed up. Sorry bout that, but you can still get across whats going on.
__________________________________________
Eugene Alfonso
GTP | Twitter | SFML | OS-Dev
thanks for your help guys - i've got this up and running now !

This topic is closed to new replies.

Advertisement