Connection testing with Perl

By Sandra Henry-Stocker  2 comments

Since I'm seldom in control of all the devices between myself and whatever system I am trying to reach, I often like to verify whether I will be able to connect to a particular port on the particular system before I concern myself with whether my connection is behaving as it should. For example, I can use a command such as "telnet remhost 9999" and then try to determine if the response I am getting is the one I was expecting. If I have appropriate access to both systems, however, I can start a process on the particular port I want to reach and then run a test to see whether I can reach that process from the other system.

A little expertise with socket I/O can come in very handy for this kind of testing. You can get by, however, with a short but handy sample Perl script like one that I have used for many such tests over the years. I call my script, derived from many Perl command examples that I've encountered on the web, "listen". Listen will open any (non-busy) port above 1023 for a normal user and any (non-busy) port for root. It requires the Socket module for the muscle work and for definitions of most of the variables used (e.g., SOCK_STREAM).

The port that you want to open must be passed as an argument or the script will complain and immediately exit.

To test a port, you would type "./listen 9999" or something like that on one system and "telnet localhost 9999" on the same server or "telnet remhost 9999" (replacing "remhost" with the actual host name of the target system) on a remote server. You should see a message acknowledging your connection on the telnet side.

boson> telnet fermion 9999
Trying 127.0.0.1...
Connected to fermion.
Escape character is '^]'.
------------------------------
You have connected to fermion
------------------------------
Connection closed by foreign host.

The script itself uses a series of commands to set up the socket, starts to LISTEN on that socket and sends the simple "You have connected" message to systems that connect to it.


#!/usr/bin/perl -w

use strict;
use Socket;

my $port = shift or die "no port specified";
my $proto = getprotobyname('tcp');
my $sysname = `uname -n`;

# create socket
socket(SERVER, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1) or die "setsock: $!";

# local port
my $paddr = sockaddr_in($port, INADDR_ANY);

# bind and listen
bind(SERVER, $paddr) or die "bind: $!";
listen(SERVER, SOMAXCONN) or die "listen: $!";
print "SERVER started on port $port ";

# accepting a connection
my $client_addr;
while ($client_addr = accept(CLIENT, SERVER))
{
# who is connecting?
my ($client_port, $client_ip) = sockaddr_in($client_addr);
my $client_ipnum = inet_ntoa($client_ip);
print "connection from: $client_ipnum";

# print message, close connection
print CLIENT "------------------------------\n";
print CLIENT "You have connected to $sysname";
print CLIENT "------------------------------\n";
close CLIENT;
}

The services that you intend to connect to on the target system are likely to be far more sophisticated than this basic Perlscript that just issues a reaffirming message and hangs up, so it may be far more difficult to interpret their responses as signifying success. Using a listen script of this sort, on the other hand, means you can get confirmation of your basic ability to connect to the remote system. You can then get your mind off wondering whether network and firewall restrictions might be interfering with what you're trying to accomplish and onto the more the painstaking testing involved with verifying whether your application is working properly.

Over the years, I have found this kind of script to be invaluable -- something like a software version of a cable tester -- and suspect it belongs in every sysadmin's bag of tricks. If you have never used this kind of script to verify connectivity, you might consider running some tests to see how easy it is to take advantage of the very useful Perl Sockets module for everyday testing.

2 comments

    Anonymous 2 years ago
    Yes, nc or netcat is a powerful utility which can do the same and much more and will be my first choice on Linux systems. However, nc is not available by default on Solaris and if you have constraints which prevent you from installing nc (for example, some crazy company policy), then this script is very handy. Thanks Sandra.
    Anonymous 2 years ago
    Nice script, but i find myself using netcat for this kind of thing:remote machine: 'nc -lp 9999'local machine: 'telent remote 9999'you should see a connection establish and then you will be able to type into the session and whatever you type will appear on the remote netcat session. you could also pipe a file into nc and it will be echoed in your telnet session:'nc -lp 999 < /etc/motd'This works on any machine with netcat installed (which I think should be default)I hope this will be useful to you at some point sandra.

      Add a comment

      Post a comment using one of these accounts
      Or join now
      At least 6 characters

      Note: Comment will appear soon after you have activated your account.
      Obscene/spam comments will be removed and accounts suspended.
      The information you submit is subject to our Privacy Policy and Terms of Service.

      ITworld LIVE

      NetworkingWhite Papers & Webcasts

      White Paper

      The 2011 iPass Mobile Enterprise Report

      This industry survey covers trends, recommendations and a policy guide on managing Enterprise Mobility for IT management and CIOs. Get data on employee device liability, as well as smartphone/tablet penetration, budget control and provisioning. Find out how your organization compares, how to ensure mobile worker productivity, and control costs.

      Webcast On Demand

      Managing Enterprise Mobility Costs

      Mobile employees, especially those traveling internationally, were spending time and resources finding and making connections. Roaming costs were out of control. The IT Administrator at The Hay Group tells you how he got more control over these costs, providing management with predictable budgets and insights while ensuring employee productivity.

      Sponsor: iPass

      White Paper

      Digital Transformation: Creating New Business Models Where Digital Meets Physical

      Individuals and businesses alike are embracing the digital revolution. Social networks and digital devices are being used to engage government, businesses and civil society, as well as friends and family.

      White Paper

      The Journey to the Private Cloud

      Both business and IT need the agility enabled by the private cloud. Now you can apply technologies and processes pioneered by public cloud services to your own data center.

      Webcast On Demand

      Navigating the Public Cloud

      InfoWorld contributing editor and consultant David Linthicum offers expert advice about choosing services to outsource to the public cloud providers, cloud data security and identity, integrating public cloud services, and how to avoid provider lock-in.

      Sponsor: Intel

      See more White Papers | Webcasts

      Ask a question

      Ask a Question