Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl -w
- use strict;
- use IO::Socket::Multicast;
- # Basic IO::Socket script to send and receive multicast messages
- # If successful, you should see the following output:
- # $ ./mcast.pl send 239.195.1.10 16384
- # Sending to 239.195.1.10:16384
- # Test packet 0 Fri Feb 27 16:24:48 2015
- # Test packet 1 Fri Feb 27 16:24:49 2015
- # Test packet 2 Fri Feb 27 16:24:50 2015
- # Test packet 3 Fri Feb 27 16:24:51 2015
- # Test packet 4 Fri Feb 27 16:24:52 2015
- #
- # $ ./mcast.pl recv 239.195.1.10 16384
- # Test packet 0 Fri Feb 27 16:24:48 2015
- # Test packet 1 Fri Feb 27 16:24:49 2015
- # Test packet 2 Fri Feb 27 16:24:50 2015
- # Test packet 3 Fri Feb 27 16:24:51 2015
- # Test packet 4 Fri Feb 27 16:24:52 2015
- sub msend {
- my $group = shift;
- my $port = shift;
- my $dest = join(":", $group, $port);
- # Subtract 1 from the local port so we don't interfere if we try to listen locally
- my $s = IO::Socket::Multicast->new(LocalPort=>$port-1) || die "$!";
- $s->mcast_if('eth0');
- $s->mcast_ttl(16);
- $s->mcast_loopback(1);
- print "Sending to $dest\n";
- my $ct = 0;
- while (1) {
- my $message = "Test packet ".$ct++." ".localtime();
- print "$message\n";
- $s->mcast_send($message, $dest);
- sleep 1;
- }
- return 0;
- }
- sub mrecv {
- my $group = shift;
- my $port = shift;
- my $s = IO::Socket::Multicast->new(LocalPort=>$port) || die "$!";
- $s->mcast_add($group, 'eth0');
- while (1) {
- my $data;
- $s->recv($data, 1024);
- print $data."\n";
- }
- return 0;
- }
- sub usage {
- print "Usage: $0 [send|recv] <group> <port>\n";
- print "Valid multicast groups are in the range 224.0.0.0 to 239.255.255.255\n";
- print "Valid ports are 1025-65535\n";
- exit 0;
- }
- my ($mode, $group, $port);
- $mode = $ARGV[0];
- $group = $ARGV[1];
- $port = $ARGV[2];
- # Basic checks on variables
- if (!defined($mode) || $mode !~ /send|recv/) { usage() }
- if (!defined($group) || $group !~ /\d{3}(\.\d{1,3}){3}/) { usage() }
- # Don't use ports less than 1025 so we don't have to worry about root privileges
- if (!defined($port) || ($port < 1025 || $port > 65535)) { usage() }
- if ($mode eq "send") { msend($group, $port) }
- elsif ($mode eq "recv") { mrecv($group, $port) }
- else { usage(); }
- 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement