Perl socket: increment port when using

I have the following code:

use IO::Socket::INET;
use Sys::Hostname;
use Socket;


my($addr)=inet_ntoa((gethostbyname(hostname))[4]);

my $port_to_use = 7777;

my $socket = new IO::Socket::INET (
        LocalHost => $addr,
        LocalPort => $port_to_use,
        Proto => 'tcp',
        Listen => 5,
        Reuse => 1
    );
die "cannot create socket $!\n" unless $socket;
my $client_socket = $socket->accept();

if I run this on one screen and run another on another screen, I get an error message:

cannot create socket Address already in use

instead of dying, I would like to try using a different port (increment by 1) until I find the one that will be used.

I tried converting the string diewith eval, but im couldn't catch it

any suggestions?

+4
source share
2 answers

, , - . . , , - , . , , ..

#!/usr/bin/env perl

use strict;
use warnings;

use Carp qw( croak );
use Errno qw( EADDRINUSE );
use IO::Socket::INET;
use Sys::Hostname qw( hostname );
use Socket;

# These can come from a config file or command line
# See also https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Dynamic.2C_private_or_ephemeral_ports
# https://unix.stackexchange.com/a/39784/2371

my @port_range = (0xC000, 0xFFFF);

my $addr = inet_ntoa( (gethostbyname(hostname) )[4]);
my $socket;

TRY_PORT:
for my $port ($port_range[0] .. $port_range[1]) {
    warn "Trying port $port\n";

    $socket = IO::Socket::INET->new(
        LocalHost => $addr,
        LocalPort => $port,
        Proto => 'tcp',
        Listen => 7,
        Reuse => 0,
    );

    if ($socket) {
        warn "Bound to port $port\n";
        last TRY_PORT;
    }

    if ( EADDRINUSE != $! ) {
        croak "Cannot bind to port '$port': $!";
    }
    warn "Port in use, trying the next one\n";
}

$socket->accept
     or croak "...";
# ...
+3

Loop:

use IO::Socket::INET;
use Sys::Hostname;
use Socket;

my($addr)=inet_ntoa((gethostbyname(hostname))[4]);

my $port_to_use = 7776;
my $fail =1;
my $socket;

while ($fail == 1){ 
    $port_to_use++;
    $fail = 0;
    warn $port_to_use;
   $socket = IO::Socket::INET->new (
        LocalHost => $addr,
        LocalPort => $port_to_use,
        Proto => 'tcp',
        Listen => 5,
        Reuse => 0
    ) or $fail =1;
}
warn $socket->accept();
+4

Source: https://habr.com/ru/post/1649250/


All Articles