perlmonks12 has asked for the wisdom of the Perl Monks concerning the following question:

Hi! I'm a new perl programmer, really new. I'm doing a basic program that use Net::SOCKS and connect over SOCKS4 with a telnet server. My code works fine, I did it based on this documentation http://search.cpan.org/~clintdw/SOCKS-0.03/lib/Net/SOCKS.pm My code simple connect to a port like 8010 and 8011 because they are the two ports that my SOCKS servers are configured, however as they are in a test environment they tend to change constantly like the port 8011 changes to a HTTP proxy and consequently SOCKS doesn't work. My solution is to connect to the port and do a connection at it with NET::Socks to make sure it works.
my $sock = new Net::SOCKS(socks_addr => $socksserver, socks_port => $s +ocksport, protocol_version => 5); my $con = $sock->connect(peer_addr => '10.1.1.3', peer_port => 23);
If the $socksserver is running a SOCKS server at port $sockspor it works great and very fast. But for example if at port $sockspor is running a HTTP proxy it takes VERY LONG to return. Like 4 minutes or so, and it's unacceptable. My idea to solve the problem is define a timeout like 10 seconds for Net::Socks connection, however there is no option at documentation and all my tests failed. Any solution please? Thank you

Replies are listed 'Best First'.
Re: Net::SOCKS how define timeout?
by ahmad (Hermit) on May 07, 2010 at 21:14 UTC

    You can always use alarm for this kind of problems

      Thanks for the reply ahmad! I was looking at alarm() and it appear to be a solution to my problem, however it breaks my code. I used like that...
      eval { local $SIG{ALRM} = sub { die "alarm\n" }; # NB \n required alarm 5; my $sock = new Net::SOCKS(socks_addr => $socksserver, socks_port => $s +ocksport, protocol_version => 5); alarm 0; }; die if $@ && $@ ne "alarm\n"; # propagate errors if ($@) { print("\nTIME-OUT\n"); } else { my $con = $sock->connect(peer_addr => '10.1.1.3', peer_port => 23); #other parts of my code. }
      Without this alarm() the application runs without errors, but with this new alarm() code I'm getting errors: Global symbol "$sock" requires explicit package name at ./test.pl line 48. Execution of ./test.pl aborted due to compilation errors. I have the main code, inside this main code I call 3 threads and inside this threads I call a function to test the connectivity, this function is where this example of code is located. I don't want to die(), well, I can call die(), but I can't exit the application, in the case of a timeout I just want to call "return" or something like that to return from this function to the previous function (the one used when I called the tread). Can you please give a help how to fix this example of code with alarm()? Thank you

        Declare the socket variable (my $sock) outside of eval so that it may be accessible outside of eval