Ethereal-dev: Re: [Ethereal-dev] ntohl(), pntohl(), g_ntohl() ?

Note: This archive is from the project's previous web site, ethereal.com. This list is no longer active.

From: Guy Harris <guy@xxxxxxxxxx>
Date: Wed, 14 Aug 2002 10:58:09 -0700
On Wed, Aug 14, 2002 at 06:59:44PM +0200, Yaniv Kaul wrote:
> What should I be using?

You left one out - "tvb_get_ntohl()".

That's the best one to use.  If you use "tvb_get_ptr()" and then extract
a bunch of stuff by hand, that throws an exception unless the *entire*
structure on which you're doing the "tvb_get_ptr()" is available in the
frame, but if you get each individual field with, for example,
"tvb_get_ntohl()", the exception won't be thrown until you fetch a field
that's not available.

That means that if you have, for example, a short frame (captured with a
snapshot length less than the length of the frame), you will get more
stuff in the protocol tree.

Of the alternatives:

	ntohl():
		requires that <netinet/in.h> (on UNIX) or <winsock2.h>
		(on Windows) be included, and Joerg Mayer is trying to
		get rid of those

		is passed a 32-bit integral value, but there's no
		guarantee that a structure pointer set from
		"tvb_get_ptr()" is properly aligned, so if you do

			structp = tvb_get_ptr(tvb, offset, sizeof (struct));

			foo = ntohl(structp->field);

		you run the risk of getting an alignment fault on many
		platforms (including the one I use at work, namely
		SPARC/Solaris)

	g_ntohl():
		doesn't require that <netinet/in.h> (on UNIX) or
		<winsock2.h> (on Windows) be included

		is passed a 32-bit integral value, but there's no
		guarantee that a structure pointer set from
		"tvb_get_ptr()" is properly aligned, so if you do

			structp = tvb_get_ptr(tvb, offset, sizeof (struct));

			foo = ntohl(structp->field);

		you run the risk of getting an alignment fault on many
		platforms (including the one I use at work, namely
		SPARC/Solaris)

	pntohl()
		doesn't require that <netinet/in.h> (on UNIX) or
		<winsock2.h> (on Windows) be included

		is passed a pointer, and dereferences it a byte at a
		time, so it's not subject to alignment restrictions

so I'd vote for "pntohl()" unless you know *for certain* that the value
you're passing is aligned on the right boundary, in which case I'd vote
for "g_ntohl()".