perl function listen

The listen function in Perl is used to mark a socket as a passive listening socket, allowing it to accept incoming connections from clients. It takes a single argument, which is the backlog size, and returns 0 on success or a false value on failure.

Here's an example that demonstrates how to use listen:

re‮ot ref‬:theitroad.com
#!/usr/bin/perl

use strict;
use warnings;
use IO::Socket::INET;

# Create a new listening socket
my $socket = IO::Socket::INET->new(
    LocalAddr => 'localhost',
    LocalPort => 12345,
    Proto     => 'tcp',
    Listen    => 5,
    ReuseAddr => 1
) or die "Cannot create socket: $!\n";

# Mark the socket as a passive listening socket
listen($socket, 5) or die "Cannot listen on socket: $!\n";

# Accept incoming connections
while (my $client_socket = $socket->accept()) {
    print "New connection from " . $client_socket->peerhost() . ":" . $client_socket->peerport() . "\n";
    # Handle the client connection here
    $client_socket->close();
}

In this example, we start by creating a new listening socket using the IO::Socket::INET module. We set the local address to "localhost", the local port to 12345, and the protocol to TCP. We also set the Listen option to 5, indicating that the socket should be marked as a passive listening socket with a backlog of 5 connections.

We then use the listen function to mark the socket as a passive listening socket. Finally, we enter a loop that accepts incoming connections and handles them appropriately. In this example, we simply print a message to the console indicating the source of the new connection, then close the socket.

When we run this script, it will listen for incoming connections on port 12345. Any client that connects to this port will be accepted, and the script will print a message indicating the source of the connection. This example is a basic skeleton for a server that can accept incoming connections, and it can be extended to perform more complex operations based on the needs of the application.