How to know data size in UDP?

Brandon S. Allbery KF8NH allbery at
Thu Oct 29 07:45:05 EDT 2009

On Oct 29, 2009, at 04:31 , Kazu Yamamoto (山本和彦) wrote:
> Since the handle is associated with UDP, the entire data size should
> be known when a UDP packet arrived. But I cannot find a way to know
> data size. (I want a function like hFileSize.) Note that hGetContents
> blocks.

The short answer is:  you can't.  You need to find a way to make  
recv() work.

Longer:  read() is intended for streams.  If you read() a datagram  
socket you may get a single packet or the system may combine packets;  
which one happens depends on the kernel implementation, and you are  
not guaranteed to have anything sane happen.  The best case for you  
would be if the system returns a single packet per system call, in  
which case you read() into a maximally sized buffer and the returned  
length is that of the actual packet.  However, many systems choose to  
retain the stream nature of read() and will return any information  
that comes in, losing the packet boundaries.

In the case of DNS, you can almost get away with this anyway because  
the protocol specifies a maximum UDP request/response length of 255  
octets sent as a single packet.  If this is insufficient, you need to  
switch to TCP.  In the case of a response, you will get a truncated  
response and will need to recognize it by parsing the data and retry  
the query over TCP.

brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at
system administrator [openafs,heimdal,too many hats] allbery at
electrical and computer engineering, carnegie mellon university    KF8NH

-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 195 bytes
Desc: This is a digitally signed message part
Url :

More information about the Glasgow-haskell-users mailing list