开发者

bash command to read from network socket?

开发者 https://www.devze.com 2023-01-27 14:10 出处:网络
I am looking for a simple bash comm开发者_开发技巧and to open a client socket, read everything from the socket, and then close the socket. Something like wget or curl for sockets.

I am looking for a simple bash comm开发者_开发技巧and to open a client socket, read everything from the socket, and then close the socket. Something like wget or curl for sockets.

Is there a command in Bash to do this? Of do I need to write a bash script?


Netcat is the tool usually used to do this, but it can also be done with the /dev/tcp and /dev/udp special pathnames.


Use nc. Its quick and easy. To connect to client 192.168.0.2 on port 999, send it a request for a resource, and save that resource to disk, do the following:

echo "GET /files/a_file.mp3 HTTP/1.0" | nc -w 5 192.168.0.2 999 > /tmp/the_file.mp3

Switch -w 5 states that nc will wait 5 seconds max for a response. When nc is done downloading, the socket is closed.

If you want to send a more complex request, you can use gedit or some other text editor to write it, save it to file "reqest", and then cat that file through the pipe to nc:

cat request.txt | nc -w 5 192.168.0.2 999 > /tmp/the_file.mp3

You don't need write a script for this, because it is a one line command... But if you will use it often, writing a script is a must!

Hope I helped. :)


The already mentioned netcat (nc) is simple and powerful. But if you need a yet more powerful tool: socat.


I had a simple case where I needed to read from a socket that may or may not have data but didn't have an EOF because the device doesn't run a webserver.

exec 3<>/dev/tcp/192.168.1.10/5000
echo -n -e '\xAA\xBB\x03\x10\x00\xEE' >&3
timeout 3 cat <&3 | od -x

Timeout takes an argument in seconds, so it'll read any data on the socket or that comes in for 3 seconds and then stop reading, which works perfectly for my use case because the only data typically in the socket is the response to a previous request.

0

精彩评论

暂无评论...
验证码 换一张
取 消