2

What is the difference between System.getenv("computername") and System.getenv("hostname") in Java?

Is there any character limit on the computer name when retrieving it using the getenv() method?

I have a lengthy hostname and System.getenv("computername") seems to be truncating it to 15 characters. OS used is Windows.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user811433
  • 3,999
  • 13
  • 53
  • 76
  • 1
    Is this specific to Java? What happens when you view the environment variable in `cmd`? – Mark Peters Nov 14 '12 at 17:32
  • this is specific to java when the value is retrieved using java code. it is fine from the cmd prompt. – user811433 Nov 14 '12 at 17:33
  • Are you suggesting that `getenv("hostname")` doesn't truncate the return value? Do you get back more than 15 characters with that environment variable? – Duncan Jones Nov 14 '12 at 17:54
  • No. Wrote a few lines of code and found that computername is for Windows env and hostname is for unix env. Still unsure about the 15 character limit. – user811433 Nov 14 '12 at 18:00

3 Answers3

1

The truncation in Windows is due to NetBIOS having a computer name length limit of 15 characters.

http://support.microsoft.com/kb/909264

G. Stevens
  • 115
  • 3
  • 5
1

This is working:

try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "Error: UnknownHostException";
}

Hope I help you.

Sam'

0

I wrote a simple test application:

public class Test {
  public static void main(String[] args) {
    System.out.println(System.getenv("computername"));
  }
}

and then executed:

set COMPUTERNAME=abcdefghijklmnopqrstuvwxyz
java Test

which printed:

abcdefghijklmnopqrstuvwxyz

Works fine in both Java 5 and 7 on Windows. No sign of truncation.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • Based on your code here, I tried setting the computername and executing the program. It works fine. I get the expected computername. But when I try to get the computername of my machine on a network I get the truncated value. – user811433 Nov 14 '12 at 18:16
  • And `echo %COMPUTERNAME%` on the command line shows the untruncated value? – Duncan Jones Nov 14 '12 at 18:17
  • No, it shows the proper value. Executing the program from cmd prompt after doing a SET also shows proper value. Only when the actual computername is long (not via SET), I see the truncated value when I execute the program from eclipse. – user811433 Nov 14 '12 at 18:22