perl on windows, how to set timeout in "use Socket" module, connect($sock, $addr) ?
- User
perl on windows, how to set timeout in "use Socket" module, connect(addr) ?
- Assistant
perl on windows, how to set timeout in "use Socket" module, connect(addr) ?
To set a timeout for the connect() function using the Socket module in Perl on Windows, you can employ non-blocking sockets combined with the select function. This approach allows you to attempt a connection without blocking your script indefinitely and to specify a maximum wait time for the connection to be established.
Below is a step-by-step guide with a complete example:
use strict;
use warnings;
use Socket;
use Fcntl;
strict and warnings: Encourage good coding practices by enforcing variable declarations and warning about potential issues.Socket: Provides low-level socket functions.Fcntl: Offers functions to manipulate file descriptors, crucial for setting non-blocking modes.my $host = 'example.com'; # Replace with your target host
my $port = 80; # Replace with your target port
my $timeout = 5; # Timeout in seconds
$host: The hostname or IP address you want to connect to.$port: The port number for the connection.$timeout: Maximum time to wait for the connection, in seconds.my $iaddr = inet_aton($host)
or die "Cannot resolve hostname $host: $!";
my $paddr = sockaddr_in($port, $iaddr);
inet_aton: Converts the hostname to a packed binary format.sockaddr_in: Prepares the socket address structure with the port and IP address.socket(my $sock, AF_INET, SOCK_STREAM, getprotobyname('tcp'))
or die "socket: $!";
socket: Creates a new socket using IPv4 (AF_INET), stream-based (SOCK_STREAM), and TCP protocol.my $flags = fcntl($sock, F_GETFL, 0)
or die "fcntl F_GETFL: $!";
fcntl($sock, F_SETFL, $flags | O_NONBLOCK)
or die "fcntl F_SETFL: $!";
fcntl: Retrieves the current flags (F_GETFL) and sets the socket to non-blocking mode by adding the O_NONBLOCK flag.my $result = connect($sock, $paddr);
if (!$result) {
# Check if the connection is in progress
if ($! == EINPROGRESS || $! == 10035) { # 10035 is WSAEWOULDBLOCK on Windows
# Proceed to wait using select
}
else {
die "connect failed immediately: $!";
}
}
connect: Attempts to establish a connection.connect may return immediately with an error indicating that the connection is in progress (EINPROGRESS on Unix-like systems or WSAEWOULDBLOCK (error code 10035) on Windows).select to Wait for the Socket to Become Writableuse constant RET_CODE =>
sub {
return exists $^E ? $^E : $!;
};
my $errno = RET_CODE->();
if ($errno == EINPROGRESS || $errno == 10035) {
# Prepare the write set
my $write_set = '';
vec($write_set, fileno($sock), 1) = 1;
# Wait for the socket to become writable or for the timeout
my $n = select(undef, my $write_set_copy = $write_set, undef, $timeout);
if ($n == 0) {
die "connect timeout after $timeout seconds";
}
elsif ($n < 0) {
die "select failed: $!";
}
else {
# Check if the socket has an error
my $sock_error;
my $sock_error_len = 4;
getsockopt($sock, SOL_SOCKET, SO_ERROR, $sock_error)
or die "getsockopt failed: $!";
if ($sock_error) {
die "connect failed: $sock_error";
}
# Connection established
}
}
select: Monitors the socket for writability, which indicates that the connection has been established or failed.vec: Manipulates the bit vector representing the set of sockets to monitor.getsockopt: Retrieves the socket error to determine if the connection was successful.After the connection is established, you may want to set the socket back to blocking mode:
fcntl($sock, F_SETFL, $flags)
or die "fcntl F_SETFL restore: $!";
print "Connected successfully to $host on port $port\n";
# Example: Send an HTTP GET request
print $sock "GET / HTTP/1.0\r\nHost: $host\r\n\r\n";
# Read and print the response
while (my $line = <$sock>) {
print $line;
}
close($sock);
Putting it all together, here's the full script:
use strict;
use warnings;
use Socket;
use Fcntl;
# Parameters
my $host = 'example.com'; # Replace with your target
my $port = 80; # Replace with your target port
my $timeout = 5; # Timeout in seconds
# Resolve hostname
my $iaddr = inet_aton($host)
or die "Cannot resolve hostname $host: $!";
my $paddr = sockaddr_in($port, $iaddr);
# Create socket
socket(my $sock, AF_INET, SOCK_STREAM, getprotobyname('tcp'))
or die "socket: $!";
# Set socket to non-blocking
my $flags = fcntl($sock, F_GETFL, 0)
or die "fcntl F_GETFL: $!";
fcntl($sock, F_SETFL, $flags | O_NONBLOCK)
or die "fcntl F_SETFL: $!";
# Attempt to connect
my $result = connect($sock, $paddr);
use constant EWOULDBLOCK => 10035; # WSAEWOULDBLOCK on Windows
use constant EINPROGRESS => 115; # EINPROGRESS on Unix-like systems
if (!$result) {
my $errno = $! + 0;
if ($errno != CORE::EINPROGRESS && $errno != EWOULDBLOCK) {
die "connect failed immediately: $!";
}
# Prepare the write set
my $write_set = '';
vec($write_set, fileno($sock), 1) = 1;
# Wait for the socket to become writable or for the timeout
my $n = select(undef, my $write_set_copy = $write_set, undef, $timeout);
if ($n == 0) {
die "connect timeout after $timeout seconds";
}
elsif ($n < 0) {
die "select failed: $!";
}
else {
# Check if the socket has an error
my $sock_error;
my $sock_error_len = 4;
getsockopt($sock, SOL_SOCKET, SO_ERROR, $sock_error)
or die "getsockopt failed: $!";
if ($sock_error) {
die "connect failed: $sock_error";
}
# Connection established
}
}
# Restore socket to blocking mode
fcntl($sock, F_SETFL, $flags)
or die "fcntl F_SETFL restore: $!";
print "Connected successfully to $host on port $port\n";
# Example usage: Send an HTTP GET request
print $sock "GET / HTTP/1.0\r\nHost: $host\r\n\r\n";
# Read and print the response
while (my $line = <$sock>) {
print $line;
}
close($sock);
Error Handling: The script checks for different error codes to determine the state of the connection. On Windows, WSAEWOULDBLOCK (error code 10035) is used instead of EINPROGRESS.
Non-Blocking Mode: Setting the socket to non-blocking ensures that the connect call doesn't block the script. After attempting to connect, select waits up to the specified timeout for the socket to become writable.
Restoring Blocking Mode: After the connection is established, it's often desirable to restore the socket to blocking mode, especially if subsequent operations assume blocking behavior.
Using High-Level Modules: While the above method uses the low-level Socket module, consider using higher-level modules like IO::Socket::INET or IO::Socket::Timeout for simpler and more portable code. These modules provide built-in support for timeouts and are generally easier to work with.
IO::Socket::INETFor comparison, here's how you could achieve the same functionality using IO::Socket::INET, which handles timeouts more gracefully:
use strict;
use warnings;
use IO::Socket::INET;
my $host = 'example.com';
my $port = 80;
my $timeout = 5; # seconds
my $socket = IO::Socket::INET->new(
PeerAddr => $host,
PeerPort => $port,
Proto => 'tcp',
Timeout => $timeout,
) or die "Cannot connect to $host:$port within $timeout seconds: $!";
print "Connected successfully to $host on port $port\n";
# Example: Send an HTTP GET request
print $socket "GET / HTTP/1.0\r\nHost: $host\r\n\r\n";
# Read and print the response
while (my $line = <$socket>) {
print $line;
}
close($socket);
Using IO::Socket::INET simplifies the process by managing non-blocking behavior and timeouts internally, allowing for cleaner and more maintainable code. If possible, prefer using such higher-level modules unless you have specific reasons to work directly with the Socket module.
Not yet included in a published release.