用JAVA去获取局域网中在线设备的需求,比如我的设备IP是192.168.1.3,我需要先判断是否在线这会你就会想到的是PING但是加上端口呢?比如我的设备IP是192.168.1.3:8080呢?根据IP加端口扫描;以下是我整理出来的解决方案:
public static Map getDeviceOnLineStatus(String networkSegment,int port){
Map map=new linkedHashMap<>();
Map resultMap=new HashMap();
if(StringUtils.isEmpty(networkSegment)){
try{
networkSegment = InetAddress.getLocalHost().getHostAddress();
}catch (Exception e){
e.printStackTrace();
}
}
int lastPoint = networkSegment.lastIndexOf('.');
String ipHead = networkSegment.substring(0, ++lastPoint);
for (int num = 1; num < 255; num++) {
String ip = ipHead + String.valueOf(num);
map.put(ip,port);
}
if(!CollectionUtils.isEmpty(map)){
Iterator> entries = map.entrySet().iterator();
while(entries.hasNext()){
Map.Entry entry = entries.next();
boolean pingIpAndPort = pingIpAndPort(entry.getKey(),entry.getValue());
System.out.println("IP为:"+entry.getKey()+",连接状态:"+pingIpAndPort);
resultMap.put(entry.getKey(),pingIpAndPort);
}
}
return resultMap;
}
public static boolean pingDeviceIp(String ip){
if(StringUtils.isEmpty(ip)){
return false;
}
if (!pingIp(ip)) {
return false;
}
int timeOut = 3000;
boolean reachable =false;
try{
reachable = InetAddress.getByName(ip).isReachable(timeOut);
}catch (Exception e){
e.printStackTrace();
}
return reachable;
}
public static boolean pingIp(String ip) {
if (null == ip || 0 == ip.length()) {
return false;
}
try {
InetAddress.getByName(ip);
return true;
} catch (IOException e) {
return false;
}
}
public static boolean pingIpAndPort(String ip, String port) {
if (null == ip || 0 == ip.length() || null == port || 0 == port.length() || !isInt(port) || !isRangeInt(port, 1024, 65535)) {
return false;
}
return pingIpAndPort(ip, Integer.parseInt(port));
}
public static boolean isInt(String str) {
if (!isNumeric(str)) {
return false;
}
// 该正则表达式可以匹配所有的数字 包括负数
Pattern pattern = Pattern.compile("[0-9]+");
Matcher isNum = pattern.matcher(str); // matcher是全匹配
if (!isNum.matches()) {
return false;
}
return true;
}
public static boolean isNumeric(String str) {
if (null == str || 0 == str.length()) {
return false;
}
if (str.endsWith(".")) {
return false;
}
// 该正则表达式可以匹配所有的数字 包括负数
Pattern pattern = Pattern.compile("-?[0-9]+\.?[0-9]*");
Matcher isNum = pattern.matcher(str); // matcher是全匹配
if (!isNum.matches()) {
return false;
}
return true;
}
public static boolean isRangeInt(String str, int start, int end) {
if (!isInt(str)) {
return false;
}
int i = Integer.parseInt(str);
return i > start && i < end;
}
测试结果:
用JAVA PING IP 网络解决方案如下:
public static boolean pingDeviceIp(String ip){
if(StringUtils.isEmpty(ip)){
return false;
}
if (!pingIp(ip)) {
return false;
}
int timeOut = 3000;
boolean reachable =false;
try{
reachable = InetAddress.getByName(ip).isReachable(timeOut);
}catch (Exception e){
e.printStackTrace();
}
return reachable;
}
演示结果:



