Bash TCP programming hack!?

I had never heard of this until I ran into working on a recent project. In “bash” you can open sockets:

exec file-descriptor<>/dev/tcp/IP-or-hostname-here/port

so for example:

exec 3<>/dev/tcp/192.168.1.100/23

would open port 23 (telnet) to IP “192.168.1.100” for read and write (the “<>”) on file descriptor “3” (remember descriptors 0, 1, and 2 are used by default for stdin, stdout, and stderr respectively, so you probably don’t want to step on them). Or if you prefer easier to read:

exec 3<>/dev/tcp/myhost.mydomain.com/telnet

and thus it’ll also do host and service lookups.

You can then write to the socket:

echo “mylogin” >&3

or read from the socket:

cat <&3

If you don’t use “<>” but rather just “<” or “>” you can open the socket only for read or write respectively.

You can also close the socket (as all good programmers should):

exec 3<&- # Close for read
exec 3>&- # Close for write

Bash – it shakes, it bakes, it does socket programming.

To note this is an entire bash-ism, you can’t simply do:

echo “hello” >/dev/tcp/192.168.1.100/23

“bash” is intercepting the “/dev/tcp” stuff and fudging it.

And I thought Perl was the only one with ugly hacks.

3 comments to Bash TCP programming hack!?

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

  

  

  

This site uses Akismet to reduce spam. Learn how your comment data is processed.