实现利用InetAddress.getByName()按计算机名称获得实验室局域网中所有开机主机名称和IP地址。import java.net.InetAddress; import java.net.UnknownHostException; public class lab1 { public static void main(String[] args) { try { // 获取本机的InetAddress实例 InetAddress localhost = InetAddress.getLocalHost(); // 获取本地网络地址前缀 byte[] address = localhost.getAddress(); String prefix = ""; for (int i = 0; i < address.length - 1; i++) { prefix += (address[i] & 0xff) + "."; } // 遍历局域网中所有可能的IP地址并获取主机名和IP地址 for (int i = 1; i <= 255; i++) { String host = prefix + i; try { InetAddress inetAddress = InetAddress.getByName(host); String hostName = inetAddress.getHostName(); String hostAddress = inetAddress.getHostAddress(); System.out.println("HostName: " + hostName + ", hostAddress: " + hostAddress); } catch (UnknownHostException e) { } } } catch (UnknownHostException e) { e.printStackTrace(); } } }分析该代码
时间: 2023-06-06 09:07:00 浏览: 141
== 0) ? prefix + "255." : prefix + address[i] + "."; } // 遍历局域网中所有可能的IP地址 for (int i = 1; i < 255; i ) { String host = prefix + i; // 通过名称获取InetAddress实例 InetAddress inetAddress = InetAddress.getByName(host); // 判断是否可达 if (inetAddress.isReachable(5000)) { System.out.println(inetAddress.getHostName() + " : " + inetAddress.getHostAddress()); } } } catch (UnknownHostException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
阅读全文