47 lines
1.6 KiB
Java
47 lines
1.6 KiB
Java
package jnet.lib;
|
||
|
||
import java.util.regex.Matcher;
|
||
import java.util.regex.Pattern;
|
||
import jnet.lib.object.PingResult;
|
||
|
||
public class PingResponseParser {
|
||
|
||
// Regex pro Windows i Linux odpovědi
|
||
private static final Pattern PATTERN = Pattern.compile(
|
||
"(?:Reply from |bytes from )?(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})" + // IP
|
||
"(?:[: ])?" +
|
||
".*?bytes=(\\d+)" + // bytes
|
||
".*?time[=<](\\d+)" + // time (může být = nebo <)
|
||
"ms" +
|
||
".*?TTL=(\\d+)", // TTL
|
||
Pattern.CASE_INSENSITIVE | Pattern.DOTALL
|
||
);
|
||
|
||
public static PingResult parse(String line) {
|
||
if (line == null || line.isEmpty()) {
|
||
return null;
|
||
}
|
||
|
||
// Zkusíme najít shodu
|
||
Matcher m = PATTERN.matcher(line);
|
||
if (m.find()) {
|
||
try {
|
||
String ip = m.group(1);
|
||
int bytes = Integer.parseInt(m.group(2));
|
||
long timeMs = Long.parseLong(m.group(3));
|
||
int ttl = Integer.parseInt(m.group(4));
|
||
return new PingResult(ip, bytes, timeMs, ttl, true);
|
||
} catch (NumberFormatException e) {
|
||
// čísla nešla parsovat – vrátíme neúspěch
|
||
return new PingResult(null, 0, 0, 0, false);
|
||
}
|
||
}
|
||
|
||
// Pokud neodpovídá úspěšné odpovědi, může to být "Request timed out." apod.
|
||
if (line.toLowerCase().contains("timed out") || line.toLowerCase().contains("unreachable")) {
|
||
return new PingResult(null, 0, 0, 0, false);
|
||
}
|
||
|
||
return null; // neznámý formát
|
||
}
|
||
} |