From 8db99052566a89779b48a79d6bb00e82d280627f Mon Sep 17 00:00:00 2001 From: Alex Harpin Date: Sat, 17 Oct 2015 17:10:22 +0100 Subject: vyatta-cfg: add port checking routine to misc.pm Add a port checking routine to Vyatta/Misc.pm to allow commits to check if a port is currently in use before allowing them. This is in connection with Bug #43, where no port checking was done on commit. --- lib/Vyatta/Misc.pm | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/Vyatta/Misc.pm b/lib/Vyatta/Misc.pm index ac1e90b..d799d23 100755 --- a/lib/Vyatta/Misc.pm +++ b/lib/Vyatta/Misc.pm @@ -30,7 +30,7 @@ our @EXPORT = qw(getInterfaces getIP getNetAddIP get_sysfs_value isIpAddress is_ip_v4_or_v6 interface_description is_local_address is_primary_address get_ipnet_intf_hash isValidPortNumber get_terminal_size get_terminal_height - get_terminal_width ); + get_terminal_width is_port_available ); our @EXPORT_OK = qw(generate_dhclient_intf_files getInterfacesIPadresses getPortRuleString @@ -234,6 +234,20 @@ sub is_local_address { return bind($sock, $sockaddr); } +# Test if the given port is currently in use by attempting +# to bind to it, success shows the port is currently free. +sub is_port_available { + my $port = shift; + my $family = PF_INET; + my $sockaddr = sockaddr_in($port, INADDR_ANY); + my $proto = getprotobyname('tcp'); + + socket(my $sock, $family, SOCK_STREAM, $proto) + or die "socket failed\n"; + + return bind($sock, $sockaddr); +} + # get list of IPv4 and IPv6 addresses # if name is defined then get the addresses on that interface # if type is defined then restrict to that type (inet, inet6) -- cgit v1.2.3