The return value of the recv () function in perl

I have a 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: $@ "; 

Recv call

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

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

Surprisingly, I did not see any return value for recv in perldoc. When I tried this myself, recv returns undef in (a), for b it is a non-printable character

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

+4
source share
2 answers

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

If you get undef, it means that recv encounters 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 "Attempting to get the LENGTH characters of data into the SCALAR variable from the specified SOCKET file descriptor. SCALAR will be grown or compressed 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

+3
source

The value returned by recv is the address and port that were 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 returned data can be determined using

 length($my_message); 
+2
source

Source: https://habr.com/ru/post/1412323/


All Articles