我正在创建一个Java项目,该项目使用java显示连接的设备的主机名,ip和mac地址。我使用的是InetAddress,但它只显示没有MAC的已连接计算机的IP和主机名,也看不到Android设备之类的已连接手机。
我在StackOverFlow上尝试了几乎所有解决方案,但是主题似乎都不起作用
public class HostDiscovery
{
private String address;
private int discoveryTimeout;
HostDiscovery( String address, int discoveryTimeout)
{
this.address = address;
this.discoveryTimeout = discoveryTimeout;
}
public Future<HostDiscoveryResult> multithreadedHostDicovery(final ExecutorService exService){
return exService.submit(() -> {
try
{
String HostName = null;
String MacAddress = null;
boolean result = InetAddress.getByName(address).isReachable(discoveryTimeout);
InetAddress ip = InetAddress.getByName(address);
if (result)
{
HostName = InetAddress.getByName(address).getHostName();
if(HostName.endsWith(".mshome.net")){
HostName = HostName.replaceAll(".mshome.net", "");
}
MacAddress = getMacAddress(ip);
}
return new HostDiscoveryResult(address, result, HostName, MacAddress);
} catch (SocketException ex)
{
return new HostDiscoveryResult(address, false, null, null);
}
});
}
private static String getMacAddress(InetAddress ip) throws UnknownHostException {
String address = null;
try {
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
address = sb.toString();
} catch (SocketException ex) {
ex.printStackTrace();
}
return address;
}
}