#!/usr/bin/env perl

use strict;
use warnings;

my $portDef = $ARGV[0];
$portDef=~m/^(\D*)(\d+)(.*)/ or die "$0: We need a start port as parameter but got none!\n";
my ($pre, $port, $post) = ($1, $2, $3);
my $used_ports = `netstat -tulan`;

my %p=();
my $addr=qr((?:\d+.\d+.\d+.\d+|[0-9a-f:]+));
for(split m/\R/, $used_ports) {
    if(m#$addr:(\d+)\s+$addr:(?:\d+|\*)\s+#) {
        $p{$1}=1;
    }
};

$port++ while $p{$port};

print "$pre$port$post"