17

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
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Bharat
  • 794
  • 1
  • 6
  • 17
  • 1
    https://www.gnu.org/software/bash/manual/bashref.html#Redirections – Jeff Schaller Apr 07 '18 at 14:45
  • thanks, but it has below this /dev/tcp/host/port If host is a valid hostname or Internet address, and port is an integer port number or service name, Bash attempts to open the corresponding TCP socket. – Bharat Apr 07 '18 at 15:23
  • This man page doesn't show how to use this bash built-in, any other ways to use this built-in – Bharat Apr 07 '18 at 15:35
  • 2
    So you're wondering why you can't use a simple command as a browser? Why don't you write this in your question? This has mostly to do with the fact that a socket is bidirectional, using the same fd, but stdin and stdout aren't expected to be by default. So commands don't expect to _read_ the result "from the output", they have to be helped with redirections. Here's an example that would work: `{ echo -e "GET / HTTP/1.0\r\nHost: www.google.com\r\n\r" >&3; cat <&3 ; } 3<> /dev/tcp/www.google.com/80`. My preference is to use specialized tools like `netcat` or `socat` – A.B Apr 07 '18 at 16:44
  • Ok, thanks..I am using this built-in to check connectivity on some ports for thounsands of nodes from a solaris box, where netcat or nc is not available. Even timeout cmd is not there, somehow using expect and this built-in I am managaing to get things done.. Didnt check for socat yet... – Bharat Apr 07 '18 at 21:05
  • have you considered using the Perl distro included w/Solaris? You may want to rephrase your question, along with noting the version of Solaris you're using. – sleepyweasel Apr 09 '18 at 22:45

1 Answers1

11

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.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250