jNetLib/src/main/java/jnet/lib/PingResponseParser.java

47 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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
}
}