用Java获取计算机名称 [英] Getting the computer name in Java
问题描述
我想知道是否有一种方法可以用Java获取计算机名称?我已经看到几个具有java.net.InetAddress
功能的答案.但是我想知道是否存在不使用网络的方法?
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??)
推荐答案
通过操作系统的基础DNS(域名系统)库从IP地址解析计算机名称".没有跨操作系统的计算机名称的通用概念,但DNS通常可用.如果尚未配置计算机名称,以便DNS可以解析它,则它不可用.
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");
}
这篇关于用Java获取计算机名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!