#!/usr/bin/perl -w
#
# Name          : mcast2bcast.pl
# 
# Version       : $Header$ 
#
# Purpose       : Capturing udp packet from a specific filter ($inputfilter) and generating udp packet with
#                 the same content.
#      
# Author        : Alexandre Dulaunoy <adulau@foo.be>
#
# Copyright (C) 2002 Alexandre Dulaunoy <adulau@foo.be>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.

use strict;
use Net::PcapUtils;
use NetPacket::Ethernet qw(:strip);
use NetPacket::IP;
use NetPacket::UDP;
use IO::Socket;

my $version = "0.0.2";
my $DEBUG = 1;
my $inputfilter = "udp and port 5001";
my $capturelenght = "1500"; 
my $capturedevice = "eth0";   			
my $destport = 1234;
my $destip = 255.255.255.255;


if ($DEBUG > 0 ) {print "mcast2bcast.pl  $version\n";}

sub process_pkt {
        my($arg, $hdr, $pkt) = @_;
	my $ip_obj = NetPacket::IP->decode(eth_strip($pkt));
	my $udp_obj = NetPacket::UDP->decode($ip_obj->{data});
	
	if ($DEBUG > 0) {
		print("View multicast packet :$ip_obj->{src_ip}:$udp_obj->{src_port} -> ",
                   "$ip_obj->{dest_ip}:$udp_obj->{dest_port} ",
                   "$udp_obj->{len}\n");
	}

	    
	my $proto = getprotobyname('udp');
	socket(SENDSOCK, PF_INET, SOCK_DGRAM,  $proto) or die "Can't open socket: $!\n";
	my $sin = sockaddr_in($destport, $destip);
	setsockopt(SENDSOCK, SOL_SOCKET, SO_BROADCAST, 1) or die "Cannot turn on the broadcast flag: $!\n";
	connect(SENDSOCK, $sin) or die "Can't connect socket: $!";
	send (SENDSOCK, $udp_obj->{data}, 0) or die "Trouble to send the broadcast packet : $!\n";
	
	if ($DEBUG > 0) {
		print("Encoded and send udp brodcast packet. packet content is : $udp_obj->{data}\n");
	}
	
	#$ip_obj->{data} = $udp_obj->encode($ip_obj);
	#my $data = $ip_obj->encode($ip_obj);
	#print $data;
}

Net::PcapUtils::loop(\&process_pkt, FILTER => $inputfilter, SNAPLEN => $capturelenght, DEV => $capturedevice);

