1

I wrote the sample client and server program using TCP protocol in Perl. So I used send() and recv() function. In that I tried to get the return value of recv() function. The sample code is,

my $return_value;
 $return_value = recv($client_socket, $data, 50, 0);
 print "return value is: $return_value\n";

When I execute my code, it doesn't print any value. For example:

return value is:

After that I read the below link, even though I didn't get any return value. return value of recv() function in perl

How could I solve this?

Thanks.

Community
  • 1
  • 1
  • http://perldoc.perl.org/functions/recv.html recv - return address of the sender if scket's protocol supports this – Sergun_spb Aug 03 '16 at 13:25
  • The return value of `recv()` is a binary value that you have to pass to `Socket::unpack_sockaddr_in()` to obtain the IP address and port. I suppose it will usually print as gibberish but it may be that it just didn't contain any printable characters in your case. You can try piping your output to `xxd` to see those. That said, while it can be mae to work `recv()` isn't actually the function of choice for TCP servers. You can just use `print()` and `<>` for line based communication or `read()`/`write()` for fancier things. – mbethke Aug 03 '16 at 14:20

1 Answers1

3

It's probably undef, indicating an error occurred[1].

use Socket qw( unpack_sockaddr_in );

defined($return_value)
   or die("Can't recv: $!\n");

my ($peer_port, $peer_addr) = unpack_sockaddr_in($return_value);

You already know the address and port of the peer with which you are communicating, so this isn't very useful. This brings up the question of why are you using recv (instead of sysread) with connected streaming protocols like TCP? Do you realize you will sometimes get less than the 50 characters you requested?


  1. Always use use strict; use warnings 'all';! If $return_value is undef, "return value is: $return_value\n" would have warned.
ikegami
  • 367,544
  • 15
  • 269
  • 518