Called in rc.local or custom wireless networking scripts, dhcphosts.pl generates an /etc/hosts file for a host on a DHCP network, allowing the use of hostnames regardless of given IP addresses. The code can also be found at http://dual.home.comcast.net/perl/dhcphosts.txt
#!/usr/bin/perl
# dhcphosts.pl - by dual
#
# Generates an /etc/hosts file for a
# box on a DHCP network
#
# - Simply call it in /etc/rc.local.
# - Depends on Nmap::Parser.
####################################
# Include Nmap::Parser
######################
use strict;
use Nmap::Parser;
# Declare and set variables
###########################
my $ip;
my $fqn;
my $dmain;
my $tld;
my $host;
my $path = '/usr/bin/nmap';
my $args = '-sP';
my @ips = qw/192.168.1.101-109/;
my $ip_addr;
my $mac_addr;
# Obtain local info
###################
my @ifconfig = `/sbin/ifconfig eth1`;
foreach my $line (@ifconfig) {
$ip = $1 if ($line =~ /inet addr:(d{1,3}.d{1,3}.d{1,3}.d{1,3})/);
}
open NETWK, ") {
$fqn = $1 if ($_ =~ /^HOSTNAME=(.+)$/);
}
close NETWK;
my @names = split (/./, "$fqn");
$host = $names[0];
$dmain = $names[1];
$tld = $names[2];
# Clobber /etc/hosts
####################
open HOSTS, ">/etc/hosts" or die "Can't open hosts: $!";
# Print local info
##################
print HOSTS "# Generated by dhcphosts.plnn";
print HOSTS "# Gotta have loopbackn";
print HOSTS "127.0.0.1tlocalhost.localdomaintlocalhostnn";
print HOSTS "# This box...n";
print HOSTS "$ipt$fqnt$hostnn";
print HOSTS "# Remaining network hostsn";
# Scan, parse and print the remaining network
#############################################
my $nmap = new Nmap::Parser;
$nmap->parsescan ($path, $args, @ips);
for my $host ($nmap->all_hosts()) {
$ip_addr = $host->addr;
$mac_addr = $host->mac_addr;
if ($mac_addr =~ /.{2}:.{2}:.{2}:.{2}:.{2}:.{2}/) {
# Fill in your MACs and hostnames here
if ($mac_addr =~ /XX:XX:XX:XX:XX:XX/) {
print HOSTS "$ip_addrthostname1.$dmain.$tldthostname1n";
}
elsif ($mac_addr =~ /XX:XX:XX:XX:XX:XX/) {
print HOSTS "$ip_addrthostname2.$dmain.$tldthostname2n";
}
elsif ($mac_addr =~ /XX:XX:XX:XX:XX:XX/) {
print HOSTS "$ip_addrthostname3.$dmain.$tldthostname3n";
}
elsif ($mac_addr =~ /XX:XX:XX:XX:XX:XX/) {
print HOSTS "$ip_addrthostname4.$dmain.$tldthostname4n";
}
}
}
# Clean up
##########
close HOSTS;
__END__
=pod
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.
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.
=cut