Java獲取本機IP地址,並根據IP地址的網段,掃描局域網里面的電腦設備;
import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; /** * 類注解 * * @author 塵世間迷茫的小書童 * @date 2020年06月23日 17:31 */ public class Demo { public static void main(String[] args) { Set<String> set = getIpAddress(); if(set.size() > 0) { set.forEach(ip -> { System.out.println("本機ip: " + ip); }); } set.remove("127.0.0.1"); scannerNetwork(set); System.out.println("掃描完畢..."); System.exit(0); } /** * 獲取本機的IP地址(包括ipv4和ipv6) <br> * 包含回環地址127.0.0.1和0:0:0:0:0:0:0:1 */ private static Set<String> getIpAddress() { Set<String> ipList = new HashSet<>(); try { Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); // 排除虛擬接口和沒有啟動運行的接口 if (netInterface.isVirtual() || !netInterface.isUp()) { continue; } else { Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = addresses.nextElement(); // if (ip != null && (ip instanceof Inet4Address || ip instanceof Inet6Address)) { // ipList.add(ip.getHostAddress()); // } if (ip != null && (ip instanceof Inet4Address)) { ipList.add(ip.getHostAddress()); } } } } } catch (Exception e) { e.printStackTrace(); } return ipList; } /** * 根據本機ip掃描局域網設備 * @param set */ private static void scannerNetwork(Set<String> set) { try { set.forEach(address -> { // 設置IP地址網段 String ips = getNetworkSegment(address); System.out.println("開始掃描 " + ips + "網段..."); String ip; InetAddress addip = null; // 遍歷IP地址 for (int i = 1; i < 255; i++) { ip = ips + i; try { addip = InetAddress.getByName(ip); } catch (UnknownHostException e) { System.out.println("找不到主機: " + ip); } // 獲取登錄過的設備 if (!ip.equals(addip.getHostName())) { try { // 檢查設備是否在線,其中1000ms指定的是超時時間 boolean status = InetAddress.getByName(addip.getHostName()).isReachable(1000); // 當返回值是true時,說明host是可用的,false則不可。 System.out.println("IP地址為:" + ip + "\t\t設備名稱為: " + addip.getHostName() + "\t\t是否可用: " + (status ? "可用" : "不可用")); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }); } catch (Exception uhe) { System.err.println("Unable to find: " + uhe.getLocalizedMessage()); } } /** * 根據ip獲取網段 * @param ip * @return */ private static String getNetworkSegment(String ip) { int startIndex = ip.lastIndexOf("."); return ip.substring(0, startIndex+1); } }