The perldoc section for getsockopt is outrageously short.
Below is the results of my search for a non-blocking connect
call.
The key item missing from any documentation that I found
was that the return value from 'getsockopt' was an integer
packed inside a string.
Armed with this I present for your viewing pleasure a code
snippet which will perform a non-blocking connect call.
Hope some of you out there find it useful.
andy
use strict;
use warnings;
use Fcntl;
use Errno;
use Socket;
use IO::Select;
my $socket;
my $flags;
my $port = 80;
my $ip = '1.1.1.1';
# create socket
socket($socket, PF_INET, SOCK_STREAM, getprotobyname('tcp')) || die("s
+ocket: $!");
# set the socket to non-blocking mode
$flags = fcntl($socket, F_GETFL, $flags) || die("fcntl: $!");
fcntl($socket, F_SETFL, $flags | O_NONBLOCK) || die("fcntl: $!");
if (! connect($socket, sockaddr_in($port, inet_aton($ip))) {
if ($!{EINPROGRESS}) {
...
run a select loop or do something else here
installing a callback handler is a good bet
...
return;
}
else {
die("connect: $!");
}
}
else {
handle_successful_connect();
}
sub callback_handler
{
my $socket = shift;
# check the error condition on the socket
my $option = getsockopt($socket, SOL_SOCKET, SO_ERROR);
if (! defined($option)) {
die("getsockopt: $!");
}
if (0 != ($! = unpack('i', $option))) {
die("connect: $!");
}
handle_successful_connect();
}
sub handle_successful_connect
{
}
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.