Wednesday, February 24, 2010

Cool Bash Trick!!!


The "/dev/tcp" trick


Bash does some super-cool magic when you access 
/dev/tcp/hostname/port. It will create a TCP socket that is connected to the named host on the given port. This lets you easily use network sockets with regular shell IO redirection. For example, the following simply prints the time from NIST:

cat < /dev/tcp/time.nist.gov/13

And YES, you can read AND write to these sockets. Here's how. The following example fetches the source for the www.google.com homepage.

exec 5<> /dev/tcp/www.google.com/80
printf "GET / HTTP/1.0\n\n" >&5
cat <&5
exec 5>&-

No comments:

Post a Comment