# tcp-monitor.pl
# Monitor a remote TCP server

sub get_tcp_status
{
# Connect to the server
socket(SOCK, PF_INET, SOCK_STREAM, getprotobyname("tcp")) ||
	return { 'up' => -1 };
local $addr = inet_aton($_[0]->{'host'});
return { 'up' => -1 } if (!$addr);
local $st = time();
local $rv;
eval {
	local $SIG{'ALRM'} = sub { die "alarm\n" };
	alarm($_[0]->{'alarm'} ? $_[0]->{'alarm'} : 10);
	$rv = connect(SOCK, sockaddr_in($_[0]->{'port'}, $addr));
	close(SOCK);
	alarm(0);
	};
return { 'up' => 0 } if ($@);
return { 'up' => $rv,
	 'time' => time() - $st };
}

sub show_tcp_dialog
{
print "<tr> <td><b>$text{'tcp_host'}</b></td>\n";
print "<td><input name=host size=25 value='$_[0]->{'host'}'></td>\n";

print "<td><b>$text{'tcp_port'}</b></td>\n";
print "<td><input name=port size=5 value='$_[0]->{'port'}'></td> </tr>\n";

print "<tr> <td><b>$text{'tcp_alarm'}</b></td>\n";
printf "<td><input type=radio name=alarm_def value=1 %s> %s\n",
	$_[0]->{'alarm'} ? '' : 'checked', $text{'default'};
printf "<input type=radio name=alarm_def value=0 %s>\n",
	$_[0]->{'alarm'} ? 'checked' : '';
print "<input name=alarm size=5 value='$_[0]->{'alarm'}'></td> </tr>\n";
}

sub parse_tcp_dialog
{
&check_ipaddress($in{'host'}) || gethostbyname($in{'host'}) ||
	&error($text{'tcp_ehost'});
$_[0]->{'host'} = $in{'host'};

$in{'port'} =~ /^\d+$/ || &error($text{'tcp_eport'});
$_[0]->{'port'} = $in{'port'};

if ($in{'alarm_def'}) {
	delete($_[0]->{'alarm'});
	}
else {
	$in{'alarm'} =~ /^\d+$/ || &error($text{'tcp_ealarm'});
	$_[0]->{'alarm'} = $in{'alarm'};
	}
}

