Friday, February 17, 2012

udp/tcp connection using pure bash


hi guys, today i am going to show you how we can open tcp or udp connection to a server using pure bash technique. let us assume that the server ip address is 192.168.0.1 and the service which we are going to connect to is web server. it binds 80 port on server. at first we should open file descriptor that will point to the remote server and port.


here is the technique of  descriptor opening by using only bash. 


exec 456<>/dev/tcp/192.168.0.1/80


now we have 456 file descriptor which is associated with server 192.168.0.1 port 80. transfering data using this file descriptor is similar to writing data into the file :) 


echo "GET / HTTP 1.0" >&456


in this example i used  tcp protocol for communication. if you want to open a connection using  udp protocol just point a file descriptor to  udp device like this


exec 786<>/dev/udp/192.168.0.1/686



that all folks.

5 comments:

Tigran said...

Didn't work for my Ubuntu.
Let's try together some day.

Luigi Rosa said...

You must remove the space between ">" and "&456".

Still unable to read from file descriptor

grawity said...

Instead of hardcoding the fd to use, it's better to let bash pick a free one:

exec {fd}<>"/dev/tcp/www.google.com/http"
# write
printf "GET / HTTP/1.0\r\n" >&$fd
printf "\r\n" >&$fd
# read until EOF
cat <&$fd
# close
exec {fd}>&-

Also, /dev/fd can be used as alternative to redirections:

echo "Hello" >/dev/fd/$fd
head -n1 </dev/fd/$fd

Unknown said...

to read the descriptor use redirection to 0 and than print $REPLY variable

for example
exec 456<>/dev/tcp/127.0.0.1/80
echo "GET HTTP / 1.0" >&456; read 0<&456
echo $REPLY

Unknown said...

thanks grawity