#!/usr/bin/perl -w
#----------------------------------------------------------------------------------------
# <path>/check_open_port.pl - checks if a remote host is reachable/open or not
#
# Copyright (c) 2014-2025  The Eisfair Team, team(at)eisfair(dot)org
#
# Creation:     31.01.2014  jed
# Last Update:  $Id$
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version..
#----------------------------------------------------------------------------------------

#========================================================================================
# main
#========================================================================================

unless (scalar(@ARGV) == 2) {
    die "Script requires two arguments\n check_open_port.pl server-name server-port\n";
}

my $debug    = 0;

my $server   = $ARGV[0];
my $port     = $ARGV[1];
my $protocol = 'tcp';
my $timeout  = 5;
my $ret_code = 0;

use Net::DNS;
use IO::Socket::INET6;

my $sock = new IO::Socket::INET6 ( Timeout => $timeout, PeerAddr => $server, PeerPort => $port, Proto => $protocol );

if ($sock) {
    if ( print $sock "HELO\n" ) {
        if ($debug) {
            print "Connection to '$server' on port '$port/$protocol' allowed.\n";
        }
    }
    close($sock);
} else {
    # Socket open failed or could not resolve hostname
    $ret_code = 1;

    my $result = Net::DNS::Resolver->new;

    # check if the hostname could be resolved to an IPv4 or IPv6 address
    if ($result->query($server, "A") || $result->query($server, "AAAA")) {
        if ($debug) {
            print "Connection to '$server' on '$port/$protocol' refused.\n";
        }
    } else {
        $ret_code = 2;

        if ($debug) {
            print "Could not resolve host '$server'.\n";
        }
    }
}

exit $ret_code;
#----------------------------------------------------------------------------------------
# end
#----------------------------------------------------------------------------------------
