Skip to content

Instantly share code, notes, and snippets.

@billagee
Last active October 2, 2015 11:08
Show Gist options
  • Save billagee/2233382 to your computer and use it in GitHub Desktop.
Save billagee/2233382 to your computer and use it in GitHub Desktop.
Perl snippet showing how to use netcat (nc) to poll a port, waiting for it to open
# Perl snippet showing how to use netcat (nc) to poll a port,
# waiting for it to open
#
# NOTE: You could also increase the value passed to -w to 60
# to do this, but you wouldn't get an up-to-the minute status
# message printed each second...
my $host = '192.168.1.100';
my $port = '443';
my $MAX_ATTEMPTS = 60; # Number of times to repeat the port check
my $attempt_count = 0;
my $result = undef;
while ($attempt_count < $MAX_ATTEMPTS) {
$result = system("nc -w 1 -z $host $port");
exit 0 if ($result == 0);
print "$host:$port not open. Sleeping...\n";
sleep 1;
$attempt_count++;
}
# If we wound up down here, then give up.
print "$host:$port never opened after $attempt_count attempts. Exiting 1.\n";
exit 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment