Bash – Different ways to use /dev/tcp/host/port command and where to find manual pages on this

bashnetworkingsolaris

What are the different ways to use /dev/tcp/host/port command and where to find manual pages on this?

< /dev/tcp/www.google.com/80

cat > /dev/tcp/www.google.com/80

Best Answer

As for the official reference to the syntax, man bash and search for the section on Redirections.

to check connectivity on some ports for thousands of nodes from a Solaris box, where netcat or nc is not available

One way, using bash's network redirection feature, would be to echo some text into that host's port and see if it was successful. Bash returns true/false based on its ability to connect to that port on that host.

Sample code, showing an array of hosts, an array of ports, and attempts to connect to those ports over TCP:

#!/bin/bash

hosts=(127.0.0.1 127.0.0.2 127.0.0.3)
ports=(22 23 25 80)

for host in "${hosts[@]}"
do
  for port in "${ports[@]}"
  do
    if echo "Hi from Bharat's scanner at $(uname -n)" 2>/dev/null > /dev/tcp/"$host"/"$port"
    then
      echo success at "$host":"$port"
    else
      echo failure at "$host":"$port"
    fi
  done
done

Since UDP is stateless, the return code from the test is not useful for scanning. You would have to use A.B's example to capture the output and see if it matches your expectations.

Related Question