Here's a version that times out on opening failures. I'm still not clear where your actual concern is, since (on my machine) opening the socket times out after 5 seconds or so, in any case. By the way, if I ping 127.0.0.x on my machines, I get a reply, and connecting to a non-existant socket returns an immediate error. I had to attempt to connect to an IP address that I *knew* didn't exist to get the timeout to occur, and set a fairly short timeout.
The reason we (I) have to use a variable and not $@ (see perldoc -f eval), is because apparently
IO::Socket sets up it's own eval() statement, and $@ never gets set. I had a version of code where the die() returned a string, and I found that although the die() was executing (determined by a print statement), $@ was not being returned correctly. Perhaps someone more enlightened than I can explain this (it's at the bottom of the node). I'm using 5.005-63 at work, and can't get to my machine at home to try it on 5.005_03.
#!/usr/local/bin/perl -w
use strict;
use IO::Socket;
{
my $timeout = 0;
my $sock = undef;
$SIG{ALRM} = sub {$timeout = 1; die};
eval {
alarm (2);
$sock = new IO::Socket::INET (PeerAddr => '10.1.1.18',
PeerPort => 29,
);
alarm (0);
};
die "Can't open socket: timeout=$timeout\n" if ($timeout or !$sock)
+;
print "I would print to the socket now, if I knew what I was connec
+ted to\n";
close ($sock);
}
#!/usr/local/bin/perl -w
use strict;
use IO::Socket;
{
my $sock = undef;
$SIG{ALRM} = sub {die "GOT TIRED OF WAITING"};
eval {
alarm (2);
$sock = new IO::Socket::INET (PeerAddr => '10.0.0.18',
PeerPort => 29,
);
alarm (0);
};
die "Can't open socket: $@\n" if (!$sock);
print "I would print to the socket now, if I knew what I was connec
+ted to\n";
close ($sock);
}
--Chris
e-mail jcwren
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.