Menu

SetComputerNameFromDnsScriptWithFallback

Juan Jose Pablos

Last modified 5 years ago Last modified on 05/05/09 14:06:33

This is another script that can be used to set the machines name (Similar to [SetComputerNameByDhcpScript]), based on whatever the reverse DNS hostname of the IP address is. (It should go in site/config.pl)

If the script can't successfully retrieve a hostname for the IP address, it will take whatever is in the unattended.txt file, and append the last section of the IP address to it - this helps to prevent duplicate machine names if we are rolling out multiple machines.

use warnings;
use strict;
use Socket;
use Net::hostent;

my $default_computer_name = $u->{'UserData'}->{'ComputerName'};
my $ip_address = $u->{'_meta'}->{'ipaddr'};
my $host = gethostbyaddr (inet_aton ($ip_address));

if (!defined $host) {
    $ip_address =~ m/^(([0-9]+).([0-9]+).([0-9]+).([0-9]+))/;
    my $default_name = $default_computer_name . $5;
        print "WARNING: Couldn't set computer name from hostname.\nComputer name set to \"$default_name\"\n";
        $u->{'UserData'}->{'ComputerName'} = $default_name;
}

else {
    my $name = $host->name ();
    $name =~ m/^(([A-Z]|[a-z]|[0-9]|-)+)(\..*)/;
    my $hostname = $1;
        print "Computer name set to \"$hostname\"\n";
        $u->{'UserData'}->{'ComputerName'} = $hostname;
}

I'm not really a coder, but I have tested it, and it seems to work fine for me! Hope it's usefult to somone!

-- Geoff Kendal - geoffatsquiggledotorg


Related

Wiki: Scripts
Wiki: SetComputerNameByDhcpScript

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.