6

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

Glen Solsberry
  • 11,960
  • 15
  • 69
  • 94
doon
  • 2,311
  • 7
  • 31
  • 52

2 Answers2

4

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

cytinus
  • 5,467
  • 8
  • 36
  • 47
  • Thanks. I did read perldoc but since I am newbie I did not understand the arguments properly. Though it is not clear why perl would not allow me to determine the reason of the error. – doon May 14 '12 at 10:36
  • 2
    You looked in the wrote docs. The docs for the IO::Socket::INET are found [here](http://search.cpan.org/perldoc?IO::Socket::INET) and its parent class is [here](http://search.cpan.org/perldoc?IO::Socket). `$sock->recv($my_message, 64)` is actually the correct usage, although `recv($sock, $my_message, 64)` should work just as well. – ikegami May 14 '12 at 15:36
3

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);
G. Allen Morris III
  • 1,012
  • 18
  • 30