I was wondering if there is a way to get the computer name in Java? I have seen several answers that feature java.net.InetAddress
. However I was wondering if there is a way that does not use the network?
(As a side question, is the computer name only a network thing anyway, so therefore has to be done this way??)
We can get the System name for a Windows or Linux machine using the getHostName() method of the InetAddress class of java.net package after getting the IP address of the system using getLocalHost() method of the same class. The class InetAddress gets the IP address of any hostname.
The getHostName() method Java InetAddress returns the host name of a corresponding IP address. If this InetAddress was created with a host name, this host name will be remembered and returned else a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service.
The hostname is what a device is called on a network. Alternative terms for this are computer name and site name. The hostname is used to distinguish devices within a local network. In addition, computers can be found by others through the hostname, which enables data exchange within a network, for example.
The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.
import java.net.InetAddress; import java.net.UnknownHostException; String hostname = "Unknown"; try { InetAddress addr; addr = InetAddress.getLocalHost(); hostname = addr.getHostName(); } catch (UnknownHostException ex) { System.out.println("Hostname can not be resolved"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With