Link to home
Start Free TrialLog in
Avatar of letharion
letharionFlag for Sweden

asked on

Get local hostname in java

I would like to get the name of the host running my code.

I use the code below.
Unfortunately, this throws the exception, so something doesn't work.
Strangely enough however, the exception is:
java.net.UnknownHostException: Sylvanas: Sylvanas
        at java.net.InetAddress.getLocalHost(InetAddress.java:1353)
        at GetXML.main(GetXML.java:10)

Which contains the answer I'm looking for: "Sylvanas"
Why do I get an exception, and why does the exception contain the answer to my question, instead of "couldn't-find-it"
try {
  java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
  System.out.println("Hostname of local machine: " + localMachine.getHostName());
} catch (java.net.UnknownHostException uhe) {
  System.out.println("Exception: " + uhe.getStackTrace());
}

Open in new window

Avatar of Mick Barry
Mick Barry
Flag of Australia image

because it can't find the ip address
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of letharion

ASKER

Ok, maybe I have misunderstood what the function does.
Is there another way to get the hostname, so I can avoid the exception?
I could in theory parse the name from the exception, but that'd be really ugly.

Otherwise I'll just pass $(uname -n) as arg when calling the program, which relies on a *nix platform, but solves my problem.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Suggest investigating why it cannot determine your ip
objects:
Is that important for any other reason? Do I have other potential problems waiting for me? Otherwise I'll just pass in the data from uname and be happy.
probably not, its a bit weird though.
Yeah, I was a bit surprised too
Thanks for the input