Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the computer name in Java [duplicate]

Tags:

java

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??)

like image 988
dann.dev Avatar asked Oct 25 '11 00:10

dann.dev


People also ask

How to get the machine name in Java code?

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.

How do I find my hostname in InetAddress?

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.

What is a hostname for a computer?

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.


1 Answers

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"); } 
like image 58
Brian Roach Avatar answered Sep 22 '22 06:09

Brian Roach