return value of recv() function in perl

doon picture doon · May 14, 2012 · Viewed 9.5k times · Source

I have non blocking UDP socket in perl created this way

my $my_sock = IO::Socket::INET->new(LocalPort => $MY_PORT,
                                     Proto => 'udp',
                     Blocking => '0') or die "socket: $@";

The recv call is

my $retValue = $sock->recv($my_message, 64);

I need to know a) when there is no data left to read b) if there is data, how much data was read c) any error conditions

Surprisingly, I didn't see any return value for recv in perldoc. When I tried it myself, recv returns undef in (a), for b it is an unprintable character

This seems to be an elementary issue. However, I still cannot find the info on googling or on stack overflow.Thanks for any inputs

Answer

cytinus picture cytinus · May 14, 2012

According to the perldoc, recv "returns the address of the sender if SOCKET's protocol supports this; returns an empty string otherwise. If there's an error, returns the undefined value."

If you are getting an undef, this means recv is encountering an error.

The error in your code is in the following line:

$retValue = $sock->recv($my_message, 64);

The function prototype for recv is:

recv SOCKET,SCALAR,LENGTH,FLAGS 

According to perldoc, recv "Attempts to receive LENGTH characters of data into variable SCALAR from the specified SOCKET filehandle. SCALAR will be grown or shrunk to the length actually read."

Try:

$retvalue = recv($sock, $my_message, 64)

This is where I got all the information: http://perldoc.perl.org/functions/recv.html