Tuesday, 31 May 2016

Getting a name for someone to connect back to your server

When doing test automation it is often the case you need to know the name of the current machine in order to prompt another machine to connect to it, particularly if you are running your tests in parallel. This week I was trying to get the server under test to connect back to a WireMock server running on the slave test machine.
The standard response on stack overflow is to use the following pattern to get a network address. In my version here if we can’t resolve the name then we are assuming we are running on a developers laptop on VPN so all the tests are run on the same machine. (Hence localhost)

String hostName = "localhost";
try {
       InetAddress addr = InetAddress.getLocalHost();
       String suggestedName = addr.getCanonicalHostName();
       // Rough test for IP address, if IP address assume a local lookup
       // on VPN
       if (!suggestedName.matches("(\\d{1,3}\\.?){4}") && !suggestedName.contains(":"))           
       hostName = suggestedName;

} catch (UnknownHostException ex) {