Hi Monks
I want to validate a port number in UNIX box. The program gets input from the user until the value is free port.
I expect the program finally give one free port number at variable '$free_port'.
But the program returns the correct free port value at first time. And returns '$freeport = 1' in number of times prompt from the user.
Please have a look in to the below output's, program, Note and give your suggestions.
Thanks
Program Output :
Please Enter the Port Number ( Default 10001 ) :
Port 10001 is currently used by another application
Please try again
Please Enter the Port Number ( Default 10001 ) : 99
Port 99 is currently used by another application
Please try again
Please Enter the Port Number ( Default 10001 ) : 111
Port 111 connected successfully
Free port is : 111
Free port is : 1
Free port is : 1
Expected Output:
Please Enter the Port Number ( Default 10001 ) :
Port 10001 is currently used by another application
Please try again
Please Enter the Port Number ( Default 10001 ) : 99
Port 99 is currently used by another application
Please try again
Please Enter the Port Number ( Default 10001 ) : 111
Port 111 connected successully
Free port is : 111
Program :
use strict;
use warnings;
use IO::Socket;
## Some Main Stuffs Here
## Get port numbers
&get_input();
## Few Remaing stuffs Here
sub get_input
{
my $default_port = "10001";
print "\nPlease Enter the Port Number [ Default $default_port
+ ] : ";
chomp(my $get_port_no=<>);
$get_port_no=($get_port_no)?$get_port_no : $default_port;
my $free_port = check_port($get_port_no);
print "\nFree port is : $free_port\n";
}
## Validate the prompted port number
sub check_port
{
my ($port)=@_;
my $host='127.0.0.1';
my $socket = new IO::Socket::INET(PeerAddr => $host.":".$port,
+ Timeout => 5);
if ($socket) {
print "\nPort $port connected successully\n";
return $port;
}
else {
print "Port $port is currently used by another applica
+tion\nPlease try again\n";
&get_input();
}
}
Note :
'netstat -an | grep LISTEN' command gives the free port number list in UNIX box.