On Linux/Unix, there actualy is no such /dev/tcp device.

$ls /dev/tcp
ls: cannot access /dev/tcp: No such file or directory

Then why we want to discuss this non exist file?

It's just one of few of the pseudo-devices in /dev that have specialized uses.

When executing a command on a /dev/tcp/$host/$port pseudo-device file, Bash opens a TCP connection to the associated socket.
A socket is a communications node associated with a specific I/O port. (This is analogous to a hardware socket, or receptacle, for a connecting cable.) It permits data transfer between hardware devices on the same machine, between machines on the same network, between machines across different networks, and, of course, between machines at different locations on the Internet.

The following examples assume an active Internet connection.

Getting the time from nist.gov via /dev/tcp

$ cat </dev/tcp/time.nist.gov/13
57702 16-11-10 06:13:20 00 0 0 613.8 UTC(NIST) *

Downloading a URL via /dev/tcp:

$ exec 5<>/dev/tcp/www.net.cn/80
$ echo -e "GET / HTTP/1.0\n" >&5
$ cat <&5

A script using /dev/tcp for troubleshooting

# dev-tcp.sh: /dev/tcp redirection to check Internet connection.
# Script by Troy Engel.
# Used with permission.

# Try to connect. (Somewhat similar to a 'ping' . . .)
echo "HEAD / HTTP/1.0" >/dev/tcp/${TCP_HOST}/${TCP_PORT}

if [ "X$MYEXIT" = "X0" ]; then
echo "Connection successful. Exit code: $MYEXIT"
echo "Connection unsuccessful. Exit code: $MYEXIT"
exit $MYEXIT

If bash was compiled with --enable-net-redirections, it has the capability of using a special character device for both TCP and UDP redirections. These redirections are used identically as STDIN/STDOUT/STDERR. The device entries are 30,36 for /dev/tcp:
mknod /dev/tcp c 30 36
From the bash reference:
If host is a valid hostname or Internet address, and port is an integer port number or service name, Bash attempts to open a TCP connection to the corresponding socket.

Comments powered by CComment