问题
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
回答1:
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
回答2:
The value returned by recv
is the address and port that that data was received from
my $hispaddr = $sock->recv($my_message, 64);
if ($retValue) {
my ($port, $iaddr);
($port, $iaddr) = sockaddr_in($hispaddr);
printf("address %s\n", inet_ntoa($iaddr));
printf("port %s\n", $port);
printf("name %s\n", gethostbyaddr($iaddr, AF_INET));
}
The length of the data returned can be determined with
length($my_message);
来源:https://stackoverflow.com/questions/10579477/return-value-of-recv-function-in-perl