#!/usr/bin/perl

# This script listens for a multicast packet containing the IP
# address of the web-server.  It then adds it to the hosts file
# and exits.

use strict;
use IO::Socket::Multicast;

$|++;

my $hostname = $ARGV[0];

open(FILE, '/etc/hosts');
my @hosts = <FILE>;
close FILE;

cleanup() if (join("\n", @hosts) =~ /$hostname\$/);

my $group = '226.1.1.2';
my $port = '2000';

my $sock = IO::Socket::Multicast->new(Proto=>'udp',LocalPort=>$port);
$sock->mcast_add($group) || die "Couldn't set group: $!\n";

while (1) {
	my $data;
	next unless $sock->recv($data,64);
	if ($data) {
		$data =~ s/(a|b|c)//g;
		open(OFILE, '>>/etc/hosts');
		print OFILE "\n" . $data . "\t" . $hostname . "\n";
		close OFILE;
		cleanup();
	}
}

sub cleanup {
	unlink('/var/lock/subsys/webIPsearch');
	exit 0;
}
