tags:

views:

47

answers:

1

I'm in the middle of of reading Internetworking with TCP/IP Vol III, by Comer.

I am looking at a some sample code for a "TIME" client for UDP.

The code gets to the point where it does the read of the response, and it takes what should be a 4 bytes and converts it to a 32 bit unsigned integer, so it can be converted to UNIX time.

"n" is a file descriptor that points to a socket that listens for UDP.

n = read (s, (char *)&now, sizeof(now));
if (n < 0)
    errexit("read failed: %s\n", strerror(errno));
now = ntohl((u_long)now);   /* put in host byte order */

What I am wondering is:

Are there some assumptions that should be checked before making the conversion? This is in C, and I am wondering if there are situations where read would pass a number of bytes that is not 4. If so, it seems like "now" would be a mess.

"Now" is defined as:

time_t   now;    /* 32-bit integer to hold time */

So maybe I don't understand the nature of "time_t", or how the bytes are passed around in C, or what situations UDP would return the wrong number of bytes to the file descriptor...

Thanks in advance.

+1  A: 

With UDP, as long as the recieve buffer you pass to read is long enough, a single UDP packet won't be broken up between read calls.

However, there's no guarantee that the other side sent a packet of at least 4 bytes - you're quite right, if a server sent only a 2 byte response then that code would leave now containing garbage.

That probably doesn't matter too much in this precise situation - after all, the server is just as free to send 4 bytes of garbage as it is to send only 2 bytes. If you want to check for it, just check that the n returned by read is as long as you were expecting.

caf
So, it sounds like you are saying I should do a length check as I read. Is this also a concern because of UDP truncation?
benc
Yes, you can check the return value of `read` to make sure it's not shorter than you expected. UDP packets shouldn't be truncated - they will be delivered intact or not at all (again, as long as the buffer you give to `read` is long enough).
caf