enumerador de portas [RESOLVIDO]

1. enumerador de portas [RESOLVIDO]

Dev
Programador_

(usa Debian)

Enviado em 03/02/2026 - 16:02h

boa tarde galera!
estou estudando java, e cheguei ao seguinte codigo

import java.io.*;
import java.net.*;
public class javap{
public static void main(String[] args){
String host = "";
BufferedReader ler = new BufferedReader(new InputStreamReader(System.in));
System.out.printf("IPv4=>");
try{
host = ler.readLine();
for(int loop = 21; loop < 65537; loop++){
Socket soc = new Socket(host, loop);
System.out.println("-Porta " +loop+ " do host " +host+ " on");
}
}
catch(IOException err){
err.printStackTrace();
}
catch(ConnectException ex){
continue;
}
}
}


não consigo terminar o programa, dá erro javap.java:19: error: continue outside of loop
o objetivo é conferir todas as portas, trazer as abertas e ignorar os erros das fechadas.
se alguem me ajudar, ficarei grato!


  


2. MELHOR RESPOSTA

Gil
gil_dev

(usa Debian)

Enviado em 05/02/2026 - 20:30h

Posso te mostrar um Utils que eu uso.

vc escreveria :

NetworkScannerUtil.findHostInNetwork(
8080, // porta
10000 // timeout
)



import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NetworkScannerUtil{


public static List<String> findHostInNetwork(int port, int timeout) {
try {

InetAddress localAddress = getLocalAddress();

if (localAddress != null) return findHostInNetwork(port, timeout, localAddress, 6);

} catch (Exception e) {}

return Arrays.asList();
}

public static List<String> findHostInNetwork(int port, int timeout, InetAddress localAddress) {

List<String> listOnvif = new ArrayList<String>();

try {

// Determinar a sub-rede
String localIp = localAddress.getHostAddress();
String subnet = localIp.substring(0, localIp.lastIndexOf('.') + 1) + "0/24";

SubnetUtils utils = new SubnetUtils(subnet);
String[] addresses = utils.getInfo().getAllAddresses();

for (String host : addresses) {
try {
InetAddress inetAddress = InetAddress.getByName(host);
if (inetAddress.isReachable(timeout)) {
try (Socket socket = new Socket(host, port)) {

listOnvif.add( host+":"+port );
} catch (IOException e) {}
}
} catch (IOException e) {}
}
} catch (Exception e) {
System.err.println("Erro ao tentar varrer Network: "+ e.getMessage());
}

return listOnvif;

}

// Método para obter o endereço IP local
private static InetAddress getLocalAddress() throws IOException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue;
}
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (inetAddress.isSiteLocalAddress()) {
return inetAddress;
}
}
}
return null;
}

public static List<String> findHostInNetwork(int port, int timeout, InetAddress localAddress, int numThreads) {

List<String> listOnvif = Collections.synchronizedList(new ArrayList<>());

try {
// Determinar a sub-rede
String localIp = localAddress.getHostAddress();
String subnet = localIp.substring(0, localIp.lastIndexOf('.') + 1) + "0/24";

SubnetUtils utils = new SubnetUtils(subnet);
String[] addresses = utils.getInfo().getAllAddresses();

// Executor com número configurável de threads
ExecutorService executor = Executors.newFixedThreadPool(numThreads);

int chunkSize = (int) Math.ceil((double) addresses.length / numThreads);

// Dividir o trabalho entre as threads
for (int i = 0; i < numThreads; i++) {
final int start = i * chunkSize;
final int end = Math.min(start + chunkSize, addresses.length);

executor.submit(() -> {
for (int j = start; j < end; j++) {
scanAddress(addresses[j], port, timeout, listOnvif);
}
});
}

// Finalizar o executor
executor.shutdown();
while (!executor.isTerminated()) {
Thread.sleep(10); // Esperar finalização
}

} catch (Exception e) {
System.err.println("Erro ao tentar varrer Network: " + e.getMessage());
}

return listOnvif;
}

private static void scanAddress(String host, int port, int timeout, List<String> listOnvif) {
try {
InetAddress inetAddress = InetAddress.getByName(host);
if (inetAddress.isReachable(timeout)) {
try (Socket socket = new Socket(host, port)) {
listOnvif.add(host + ":" + port);
} catch (IOException ignored) {
}
}
} catch (IOException ignored) {
}
}
}


3. Re: enumerador de portas

Buckminster
Buckminster

(usa Void Linux)

Enviado em 05/02/2026 - 13:22h

O erro provavelmente acontece porque o bloco try-catch está dentro do laço for, mas o comando continue tenta interagir com o laço a partir de um escopo onde ele não é reconhecido (dentro do catch).
Além disso, para que o programa continue testando as próximas portas após encontrar uma fechada, o try-catch deve envolver apenas a tentativa de conexão, e não o laço inteiro.

Segue uma sugestão não testada:

import java.io.*;
import java.net.*;

public class javap {
public static void main(String[] args) {
String host = "";
BufferedReader ler = new BufferedReader(new InputStreamReader(System.in));

System.out.printf("IPv4=>");
try {
host = ler.readLine();
for (int loop = 21; loop < 65535; loop++) {
// O try deve ficar dentro do for para ignorar o erro e seguir para a próxima porta
try {
// Define um timeout curto (ex: 200ms) para o scanner não travar em portas filtradas
Socket soc = new Socket();
soc.connect(new InetSocketAddress(host, loop), 200);
System.out.println("- Porta " + loop + " [ABERTA]");
soc.close();
} catch (IOException ex) {
// Se der erro (porta fechada ou timeout), o loop continua automaticamente
// Não é necessário usar 'continue' aqui, pois já é o fim do bloco do for
}
}
System.out.println("Scan finalizado.");
} catch (IOException err) {
err.printStackTrace();
}
}
}

Tu pode implementar Threads para tornar esse mapeamento de portas mais rápido.

_________________________________________________________
Rule number one: Always listen 'to' Buck!
Enquanto o cursor estiver pulsando, há vida!


4. Re: enumerador de portas [RESOLVIDO]

Gil
gil_dev

(usa Debian)

Enviado em 05/02/2026 - 20:25h


O java permite vc verificar se o host e acessivel, primeiro, antes de testar a porta, por exemplo:


int timeout = 500; // 0.5 segundos
InetAddress inetAddress = InetAddress.getByName(host);
boolean isReachable = inetAddress.isReachable(timeout)
if(isReachable){
try (Socket socket = new Socket(host, port)) {
// Aqui Oque vc faz quando a porta esta aberta
} catch (IOException ignored) { /* exceção ou caso a porta esteja fechada */ }
}


Se vc quiser fazer um loop para verificar quais portas estão disponiveis, pesquise uma coisa chamada ExecutorService, para configurar o numero de threads.










Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts