15

I've got a build.gradle task that works like a champ on my dev box at producing a properties file that records the name of the machine that the build was generated on. The logic is simple enough...

def hostname = InetAddress.getLocalHost().getHostName();

On my dev box this always produces the same value as if I did hostname from the bash shell.

bobk-mbp:DM_Server bobk$ hostname
bobk-mbp.local

On our jenkins CI server, however, bash hostname returns one thing, but my call to InetAddress.getLocalHost().getHostName(); returns something else. What needs to change on the jenkins machine to get these two returning the same value?

Bob Kuhar
  • 10,838
  • 11
  • 62
  • 115

2 Answers2

14

Assuming you're on linux, the hostname command executed from the o/s returns the kernel's configured hostname.

InetAddress.getHostName() is doing a reverse lookup on the server's IP address using the naming service (DNS) configured in your O/S.

If you need the hostname as understood by the o/s, getting it from an environment variable via System.getenv may be the simplest option. It isn't a completely robust way to do this but it may be enough without needing to delve into network or system admin.

Brian Smith
  • 3,383
  • 30
  • 41
  • 1
    This is pretty much it. Even simpler than the environment variable is shelling out of gradle to exec hostname ( "hostname".execute().text ). Works for me. Thanks. – Bob Kuhar Jun 21 '12 at 20:15
  • I had to use `"hostname".execute().text.trim()` to remove the trailing newline character. – friederbluemle Jun 27 '16 at 11:47
8

From the API documentation for InetAddress.getHostName();

If this InetAddress was created with a host name, this host name will be remembered and returned; otherwise, a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service. If a lookup of the name service is required, call getCanonicalHostName.

So you may need to configure the DNS on the Jenkins server. The easiest way to do this is to edit /etc/hosts (I'm assuming your Jenkins runs on Linux) and make sure it looks like this:

127.0.0.1           localhost       localhost.localdomain
<public IP address> <hostname>      <hostname>.<domain>
gareth_bowles
  • 20,760
  • 5
  • 52
  • 82
  • Hmmm. Our /etc/hosts looks a lot like that [127.0.0.1 localhost.localdomain localhost] but the output of InetAddress.getHostName() is "ab". I'm leaning towards "hostname".execute().text and calling it good. – Bob Kuhar Jun 21 '12 at 19:34
  • 2
    This is actually backwards from the desired order of /etc/hosts, the canonical name (with domain) element should come before hostname. http://man7.org/linux/man-pages/man5/hosts.5.html – NoUserException Nov 06 '15 at 18:46