#!/usr/bin/perl -w
#
# portping - ping a TCP port on a server, ssh by default. 
#            Perl, Unix/Linux/Windows...
#
# This program works by trying to establish a TCP connection, no ICMP 
# is used. This can be useful in senarios where everything but ssh 
# has been blocked by firewalls.
#
# 23-Jan-2006, ver 0.65
#
# USAGE:    portping [-h] | hostname [port]
#           
#           -h              # print help
#           hostname        # host to TCP ping
#           port            # port number to use (default is 22)
#    eg,
#           portping mars          # try TCP port 22 (ssh) on mars
#           portping mars 21       # try TCP port 21 on mars
#
# There are currently no advanced options for port scanning or different 
# TCP flags, as there are many existing freeware tools to do this. 
# portping is designed to be a simple handy perl script.
#
#
# SEE ALSO: nmap (port scanner), hping2 (super ping)
#
# COPYRIGHT: Copyright (c) 2004 Brendan Gregg.
#
#  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.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#  (http://www.gnu.org/copyleft/gpl.html)
#
# 25-Mar-2004   Brendan Gregg   Created this.
# 23-Jan-2006      "      "     Tweaked style.

use strict;
use IO::Socket;

#
#  Command line arguments
#
my $host = defined $ARGV[0] ? $ARGV[0] : "";
usage() if $host =~ /^(-h|--help|)$/;
my $port = defined $ARGV[1] ? $ARGV[1] : 22;    # default port

#
#  Try to connect
#
my $remote = IO::Socket::INET->new(
    Proto    => "tcp",
    PeerAddr => $host,
    PeerPort => $port,
    Timeout  => 8,
);

#
#  Print response
#
if ($remote) {
    print "$host is alive\n";
    close $remote;
    exit 0;
}
else {
    print "$host failed\n";
    exit 1;
}

# usage - print usage message and exit
#
sub usage {
    print STDERR "USAGE: portping [-h] | hostname [port]\n";
    print STDERR "   eg, portping mars      # try port 22 (ssh) on mars\n";
    print STDERR "       portping mars 21   # try port 21 on mars\n";
    exit 1;
}
