Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl socket: increment port if in use

Tags:

sockets

perl

eval

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 start this in one screen and start another one in the other screen, i get an error:

cannot create socket Address already in use

instead of dying, i would like to try using different port (increment by 1) until it can find the one to use.

I've try to convert the die line with eval but im not able to catch it

any suggestions?

like image 656
ealeon Avatar asked Mar 12 '23 14:03

ealeon


1 Answers

Use a 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();
like image 59
Jens Avatar answered Mar 20 '23 02:03

Jens