Perl proxy
This is intended to be a short article demonstrating HTTP and SOCKS proxy usage in perl, mostly by two code snippets.
http method
This method requires LWP.
use LWP::UserAgent;
my $ua = LWP::UserAgent->new();
$ua->proxy( ['http'], "http://$ip:$port/" );
$ua->timeout(5);
my $resp = $ua->get( "http://www.s5h.net/datafile" );
if( !$resp->is_success ) {
return(0);
}
Now the $resp HTTP::Response object holds the response data.
SOCKS method
This requires Net::SOCKS, available from CPAN if you don't already have this available, also consider looking at the perl user space page.
Unfortunately I've found this object often fails to timeout, therefore I have found that I've required an alarm handler to pick up the timeouts.
my $sock = new Net::SOCKS(socks_addr => $ip,
socks_port => $port,
user_id => 'the_user',
user_password => 'the_password',
force_nonanonymous => 0,
protocol_version => 5
);
my $f = $sock->connect( peer_addr => "finger.kernel.org", peer_port => 79 );
while( <$f> ) {
..
}
$sock->close();
This is all well and good, however, we need to handle the occasions when the remote host doesn't answer. In order to do this you can follow the example below.
alarm signal
This is just a simple example using eval.
eval {
local $SIG{"ALRM"} = sub { die "connect timed out" };
alarm(5);
my $sock = new Net::SOCKS(...);
my $f = $sock->connect( ... );
$sock->close();
};
alarm(0);
if( $@ ) {
die( $! );
}
There you have it in the above the timeout can be dealt with.
What is also worth noting is that IO::Select can also be used in conjunction with the file handle if you have multiple connections going through a gateway.