简体   繁体   中英

listen for returning UDP packets in bash

I played around with bash(4.0.33) network support for learning purposes and tried to create a port scanner in bash. For TCP I opened a TCP/IP socket with

exec 3<>/dev/tcp/192.0.2.1/80

and appropriate action was taken if the connection was refused or connect system call timed out. However, with UDP I'm easily able to send a packet with

echo > /dev/udp/192.0.2.1/53

but how to read returning packets from correct socket? I mean UDP datagram sent to 192.0.2.1 has source port from ephemeral port range and thus I do not know which socket in /dev/udp/192.0.2.1/ directory should I read. Or isn't this doable without external utilities like tcpdump ?

Bash's UDP support isn't great, and is compiled out on many distros (Debian/Ubuntu and derivatives especially). The recommended tool is netcat:

nc -u 192.0.2.1 53

Note: Use coproc or named pipes to read and write from the same netcat process. Don't send a packet first and try to catch the reply netcat.

Bash is really the wrong language for this though. Consider using Python, which handles both UDP and binary data way better, with just a couple of more lines of code.

"bash is definitely not the right choice for this"
"Bash is really the wrong language for this though"
Not sure why this is asserted (depending on disto). This works for me on a pi-ZW:

#!/bin/bash
while true; do 
  nc -lu 16523 | (read line; 
  echo $line
  cmd=${line:0:9}
  echo $cmd
  if [ "$cmd" == "Send Date" ] ; then
    dt="!!D$(date +%y%m%d)"
    echo $dt > /dev/udp/192.168.2.165/16523
  elif [ "$cmd" == "Send Time" ] ; then
    tm="!!T$(date +%H%M%S)"
    echo $tm
    echo $tm > /dev/udp/192.168.2.165/16523
  else
    sleep 1s
    echo $line >> /home/pi/udp16523.log
  fi)
done

Then another process can, say hourly, send the time with
echo "!!T$(date +%H%M%S)" > /dev/udp/192.168.2.165/16523

I did have to turn off history expansion with "set H+" in /etc/rc.local to handle the unexpected (by me) expansion of ! within quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM