If Perl is an option, you can use its IO::Socket
module to test a connection to a particular host and port; the script below hard-codes TCP as the protocol (which is what telnet would use):
#!/usr/bin/perl -w
# tries to connect to the given IP and port (tcp)
use strict;
use IO::Socket;
my $desthost = shift or die "Usage: $0 host port\n";
my $destport = shift or die "Usage: $0 host port\n";
gethostbyname($desthost) || die "Invalid host given\n";
my $handle = IO::Socket::INET->new(
PeerAddr => $desthost,
PeerPort => $destport,
Proto => 'tcp')
or die "can't connect to $desthost:$destport: $!\n";
close $handle;
print "Success!\n"
Sample output from a closed port:
$ ./above-script kafka02 6667
can't connect to kafka02:6667: Connection refused
Sample output from an open port:
$ ./above-script kafka02 4200
Success!
telnet
utility turns off the protocol behaviour if a port is given at command line. Then it behaves much likenetcat
, just with line ending detection.