/
mmarakayeva
/
lab5
Обзор
Документация
Войти
/
mmarakayeva
/
lab5
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/NetworkScanner.java
114 строк
5 KB
Миленикс
first_commit
14 июн 2026, 18:31
14 июн 2026, 18:31
2299a42
Код
Авторство
О чём код?
import java.io.*; import java.net.*; import java.util.concurrent.*; /** * Сканер сети для поиска эхо-серверов */ public class NetworkScanner { private static final int PORT = 12345; private static final int TIMEOUT = 500; // ms private static final int THREAD_COUNT = 50; public static void main(String[] args) { System.out.println("========================================"); System.out.println(" ПОИСК СЕРВЕРОВ В СЕТИ"); System.out.println("========================================"); System.out.println("Сканируем порт " + PORT + " в подсети..."); System.out.println("========================================\n"); try { String myIp = getMyIp(); String baseIp = getBaseIp(myIp); System.out.println("Ваш IP: " + myIp); System.out.println("Сканируемая подсеть: " + baseIp + ".*\n"); System.out.println("Поиск... (это может занять некоторое время)\n"); ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); ConcurrentLinkedQueue<String> foundServers = new ConcurrentLinkedQueue<>(); CountDownLatch latch = new CountDownLatch(254); for (int i = 1; i <= 254; i++) { String ip = baseIp + i; // Пропускаем свой IP if (ip.equals(myIp)) { latch.countDown(); continue; } final String targetIp = ip; executor.submit(() -> { try { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(targetIp, PORT), TIMEOUT); foundServers.add(targetIp); System.out.println("✓ НАЙДЕН сервер на " + targetIp + ":" + PORT); // Пробуем получить ответ try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { out.println("ping"); String response = in.readLine(); System.out.println(" → Ответ: " + response); } } } catch (IOException e) { // Сервер не найден - игнорируем } finally { latch.countDown(); } }); } latch.await(); executor.shutdown(); System.out.println("\n========================================"); System.out.println(" РЕЗУЛЬТАТЫ СКАНИРОВАНИЯ"); System.out.println("========================================"); System.out.println("Найдено серверов: " + foundServers.size()); if (foundServers.isEmpty()) { System.out.println("Эхо-серверы на порту " + PORT + " не обнаружены."); System.out.println("Убедитесь, что сервер запущен на другом компьютере."); } else { System.out.println("\nСписок найденных серверов:"); for (String server : foundServers) { System.out.println(" • " + server + ":" + PORT); } } } catch (SocketException e) { System.err.println("Ошибка получения IP-адреса: " + e.getMessage()); } catch (InterruptedException e) { System.err.println("Сканирование прервано: " + e.getMessage()); } System.out.println("\nСканирование завершено."); } /** * Получение IP-адреса текущего компьютера */ private static String getMyIp() throws SocketException { try { InetAddress localHost = InetAddress.getLocalHost(); return localHost.getHostAddress(); } catch (UnknownHostException e) { throw new SocketException("Не удалось определить IP-адрес"); } } /** * Получение базового IP подсети (первые три октета) */ private static String getBaseIp(String fullIp) { int lastDot = fullIp.lastIndexOf('.'); if (lastDot != -1) { return fullIp.substring(0, lastDot); } return "192.168.1"; } }