我正在尝试使用 Java 获取网络中连接的远程 PC 名称和 IP 地址。我能够获取 IP,但无法获取设备名称。我附上代码供引用。
Java 代码:
import java.io.IOException;
import java.net.InetAddress;
public class findIP {
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
String N = localhost.getHostName();
for (int i = 1; i <= 254; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
InetAddress name = InetAddress.getByName(N);
if (address.isReachable(1000))
{
System.out.println(address+" " +"Device Name: "+name);
}
最佳答案
首先,InetAddress.getByName(N)
正在尝试解析您的服务器主机名,而不是客户端。所以你的代码应该反射(reflect)你的意图:
String name = address.getHostName();
现在回答您的问题,InetAddress.getHostName()
将返回相应 IP 地址的反向 DNS 查找结果。并非您应用程序的所有客户端都会有 DNS 记录,因此您可能看不到“设备名称”。
关于java - 使用 Java 的远程 PC 名称和 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50274044/