Generating a random hostname

Matthew Seaman m.seaman at
Thu Mar 18 13:37:42 UTC 2010

Hash: SHA1

On 18/03/2010 11:57:56, Peter Steele wrote:
>> Thinking about this some more, a good trick would be to generate a
>> hostname from the MAC address of the host, since that is guaranteed
>> to be unique.
> In fact, this is what we are currently using. Unfortunately I guess I
> wasn't entirely clear. I was looking for a facility that actually
> *assigns* a random hostname, similar to what's provided in Windows.
> Generating the string itself obviously can be done in any number of
> ways, but once you have the string, there are at least of couple of
> files where this name needs to be inserted (/etc/hosts,
> /etc/rc.conf). When you create a master image in Windows, you can
> have it automatically assign a random hostname the first time the
> cloned image is booted. That's what I was looking for. My guess is
> that I'm going to have to update these files manually, running a
> script for example via rc.conf that disables itself after the first
> time the system boots.

Ahah!  Why didn't you say so?

That's pretty simple really.  Once you've generated the hostname, just
use hostname(1) to make it the live name of the machine.

This would have to be done with a small shell script, yes.  Probably the
easiest way to do that is a small RC script set to run just before
/etc/rc.d/hostname, and that stole^Wborrowed most of the logic from that
script about kenv and DHCP names, and hostname already being set.
The core actions that script has to do are:

if [ -z ${hostname} ] ; then
	hostname=$( generate_hostname )
	/bin/hostname "${hostname}"
        echo hostname=\"${hostname}\" >> /etc/rc.conf

Once hostname is set in /etc/rc.conf, this script will do nothing, and
the regular /etc/rc.d/hostname script will operate normally.

Setting the hostname with /bin/hostname is all that is specifically
necessary for the local machine.  It doesn't really need to be added to
/etc/hosts, although that's not a bad idea.

An alternative might be to run everything using DHCP and get the DHCP
server to generate names and dish them out to the clients.

Of course, it would be good to add the new hostname to some sort of
networked database, like the DNS or NIS or LDAP so that other hosts can
know how to get to it, but that's a different problem.



- -- 
Dr Matthew J Seaman MA, D.Phil.                   7 Priory Courtyard
                                                  Flat 3
PGP:     Ramsgate
                                                  Kent, CT11 9PW
Version: GnuPG/MacGPG2 v2.0.14 (Darwin)
Comment: Using GnuPG with Mozilla -


More information about the freebsd-questions mailing list