dann.dev dann.dev - 1 year ago 166
Java Question

Getting the computer name in Java

I was wondering if there is a way to get the computer name in Java? I have seen several answers that feature

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

Answer Source

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";

    InetAddress addr;
    addr = InetAddress.getLocalHost();
    hostname = addr.getHostName();
catch (UnknownHostException ex)
    System.out.println("Hostname can not be resolved");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download