20 Apr 2012 @ 8:00 PM 

If you happen to write some scripts for sftp, ftp (…) files transfer, you might want to check if the remote host does accept the connection on the port you specify before triggering anything.

What’s the point of doing this test? – it can be discussed, actually. But one might prefer to handle the case where the host is not responding or refusing the connection otherwise than by parsing the answer provided through the command line by the sftp, ftp (sftp..) binary.

That’s what I wanted to do and my next challenge was to find a way to do this test without using telnet, ftp, sftp, ssh (etc.). The thing is most of the example you can find on the web are using these commands.

The trick is to use the bash sockets…And especially this one: /dev/tcp/. We can try to write something in the socket


and depending on the success or failure assume we could connect… or not. For example, let’s do the following:

exec 3>/dev/tcp/ && echo “OK”

If the connection is not sucessful you will have the answer:

unix:solaris> exec 3>/dev/tcp/ && echo “OK”
-bash: connect: Connection refused

And if it can connect it will simply print in your screen “OK”:

unix:solaris> exec 3>/dev/tcp/ && echo “OK”

The return codes will be “1” when unsuccessful and “0” when successful.

Then it’s up to you to wrap up that command in your function and properly handle the errors/exception/log.

One example of a full test function:

[[ $VERBOSE = TRUE ]] && doVerbose “Testing the connection to the server …”
res=”not Connected”

# Note: return is 0 if sucessful and 1 is unsucessful
`exec 3>/dev/tcp/${REMOTE_DEST}/${REMOTE_PORT}` && res=”Connected” || res=”not Connected”
if [[ ${res} != “Connected” ]]
doLog “Cannot connect to ${REMOTE_DEST}/${REMOTE_PORT}…[FAILURE]”
quit “Cannot connect, server ${REMOTE_DEST}/${REMOTE_PORT} does not accept the connection”
doLog “${res}…[OK]”


  1. doLog, quit, doVerbose are functions within the same script dedicated to handle the log files, manage exits and finally manage the verbose mode, if triggered while executing the script.
  2. ${REMOTE_DEST} and ${REMOTE_PORT} are variables set outside the fuction.

To go further:

/dev/tcp is one of the pseudo-device unix like systems have. We are more familiar with /dev/null when for example we are only interested with the STDOUT stream and not STDERR (the famous 2>/dev/null) but there are actually a few of them: /dev/zero, /dev/random, /dev/full for example.

You can read the wikipedia page on device files that is quite interesting.

Posted By: Nicolas
Last Edit: 20 Apr 2012 @ 10:38 AM

EmailPermalinkComments (0)
Tags: , , ,
Categories: Bash, Snippets

 Last 50 Posts
Change Theme...
  • Users » 67
  • Posts/Pages » 25
  • Comments » 4
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight