Re: [gnet] sizeof buffer recived whit udp socket



On Wed, Feb 04, 2004 at 04:15:17PM -0000, Rodrigo Cabeceiras wrote:

> I?m using the udp socket examples of gnet, i recive a ?gchar
> buffer[1024]?, but my buffer is a xml and to parse it I can not have
> more data in the buffer other than xml itself. So the buffer I receive
> is 1024 long and contains 150 chars (that is the size of my xml). Hoe
> can I reduce de buffer from 1024 to the size odf what is inside?    Can
> I copy the buffer until the ?\0? (EOF), so that when I pass the parser
> it receives only xml data?

The actual size of the buffer should be irrelevant. Either the XML
parser needs to be told how many bytes (or characters) it should parse,
or it will parse all data up to a terminator, typically NUL (0x00).

C doesn't have a facility to pass an entire array to a function, only
a pointer to the start of the array. It's up to the function to decide
how long it is; either by assuming a particular length or, more
commonly, by having an extra parameter to indicate the length of the
array/buffer/string. Some functions (such as strcmp()) assume the data
is terminated with a special character, and so don't need to be told
the length of the buffer explicitly.

Typically you'll have a function which looks like:

  parse_xml_buffer (const char *buffer, int length)

In this case, 'buffer' is just the start of the data you received, and
'length' is the number of bytes you received. It doesn't matter if the
buffer is 1500 bytes and you tell the function the length is 150; it
has no way of knowing the actual size of the buffer, and will only try
to parse what you told it to.  The inverse applies too: if the buffer
is 1500 bytes and you tell the function it's 40000, it will try to parse
data beyond the end of the buffer, typically resulting in the program
crashing.

I seem to recall the UDP functions return the length of the received
data, so you should be able to just use that for the size. If it says
you received more than you were expecting, you should print out the
buffer (or use something like ethereal to view the network traffic)
and see exactly what it is you're receiving.

Mike.

Attachment: signature.asc
Description: Digital signature



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]