#!/bin/sh
# Script to monitor UDP packets via tcpdump

BROADCAST=")"

# Read arguments from the command line
while [ $# -ge 1 ]; do
	case $1 in
		"nomulticast")
			MULTICAST=" and not multicast"
			;;
		"multicast")
			MULTICAST=" or multicast"
			;;
		"broadcast")
			BROADCAST=" or ip broadcast)"
			;;
		"data")
			DATA="-X -s 1600 "
			;;
		"save")
			SAVE="-w /tmp/ip.log "
			;;
		"read")
			ARGS="$DATA-r /tmp/ip.log"
			tcpdump $ARGS
			exit
			;;
		*)
			if [ "$ARGS" = "" ]; then
				ARGS="(icmp or udp) and ((net $1"
			else
				ARGS="$ARGS and not net $1"
			fi
			;;
	esac
	shift
done

if [ "$ARGS" = "" ]; then
	echo ""
	echo "Usage: ipmon capture [exclude] [exclude...] [nomulticast/multicast] [broadcast] [data] [save]"
	echo " - capture     = ip address to capture"
	echo " - exclude     = list of ip address(es) to exlude"
	echo " - nomulticast = not to see ANY multicast"
	echo " - multicast   = to see all the multicast (even those not from the captured address)"
	echo " - broadcast   = to see all the broadcast (even those not from the captured address)"
	echo " - data        = to see the data of the packets"
	echo " - save        = don't show anything but save the result in the file /tmp/ip.log"
	echo ""
	echo "Usage: ipmon [data] read  ==> to read the file saved with a previous ipmon command"
	echo " - data        = to see the data of the packets"
	echo ""
	echo "Examples:"
	echo " ipmon 192.168.3.106 192.168.3.12 nomulticast"
	echo " ipmon 192.168.3.106 data save"
	echo " ipmon data read"
	echo ""
	echo "ATTENTION: the capture will stop automatically after 2000 messages."
	echo "To stop prematurely, press Ctrl+C !"
	echo ""
	exit
fi

if [ "$MULTICAST" != "" ]; then
	ARGS="$ARGS$MULTICAST"
fi
ARGS="-c 2000 $DATA$SAVE$ARGS)$BROADCAST"
#echo "$ARGS"
tcpdump $ARGS

