dae galera,
como eu faco pra verificar se uma determinada porta jah esta sendo usada pelo sistema??
vlw
Portas
5 Respostas
Programaticamente falando, é só abrir um Socket e fechá-lo em seguida. Se detonar uma exceção, é porque não existe a porta:
Socket socket = new Socket(“127.0.0.1”, 9999);
Será que existe outra maneira???
com o Socket funcionou… mas levava 1 sec pra testar cada porta, e a intencao do prog era testar todas as 65000, o q tornou usar Socket inviavel… entaum eu usei DatagramSocket, dai funcionou exatamente como eu queria
vlw
Foi mal, esqueci totalmente desta classe mano. Ela serve exatamente para isso.
Não sei se já não é muito tarde pra falar sobre isso…
Mas mesmo assim gostaria de dar uma idéia…
Se vc já não conseguiu solucionar esse problema, acho que a criação de algumas threads seria a solução.
Mas caso vc conseguiu achar uma maneira mais eficaz, dá um toque porque eu também me interesso no assunto.
Valeu,
Maicon
Bom scan para todos:
/*
* @(#)NetUtils.java
*
* Copyright 2003 by Amichai Rothman. All Rights Reserved.
*
* Contact: [email removido]
*
*/
import java.net.*;
import java.io.*;
import java.util.*;
/**
* <b>NetUtils</b> is a network utility class. <p>
*
* @author Amichai Rothman
* @version 1.1, 02/01/27
*/
public class NetUtils {
/**
* Communicates with given host on given port, sending data from several files,
* one file at a time, and saving the response to each in a separate file.
*
* @param host the name of the host to whom data will be sent.
* @param port the target port on host where data will be sent.
* @param infiles the names of files containing data to be sent.
* @param outfiles the names of files where responses will be saved.
*/
public static void doSession(String host, int port, String[] infiles, String[] outfiles)
throws IOException {
Socket sock = null;
try {
// open socket
System.out.println("Opening socket to " + host + ':' + port);
sock = new Socket(host,port);
sock.setSoTimeout(30000);
// send and receive all files in session
for (int i = 0; i < infiles.length; i++) {
System.out.println("Sending " + infiles[i] + " receiving " + outfiles[i]);
send(sock,infiles[i],outfiles[i]);
}
System.out.println("Done");
} finally {
if (sock != null) {
try {
System.out.println("Closing socket");
sock.close();
} catch (IOException ioe) {
System.out.println("Can't close socket");
ioe.printStackTrace();
}
}
}
}
/**
* Sends a file's content to a given socket, saving the response to a file.
*
* @param sock the socket to communicate through.
* @param infile the name of a file containing data to be sent.
* @param outfile the name of a file where the response will be saved.
*/
public static void send(Socket sock, String infile, String outfile)
throws IOException {
BufferedInputStream inf = null;
BufferedOutputStream outf = null;
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
// initialize
in = new BufferedInputStream(sock.getInputStream());
out = new BufferedOutputStream(sock.getOutputStream());
inf = new BufferedInputStream(new FileInputStream(infile));
outf = new BufferedOutputStream(new FileOutputStream(outfile));
int count;
byte[] data = new byte[1024];
// send data
while ((count = inf.read(data)) != -1)
out.write(data,0,count);
out.flush();
// receive response
while ((count = in.read(data)) != -1)
outf.write(data,0,count);
count = 0;
} finally {
if (inf != null)
inf.close();
if (outf != null)
outf.close();
}
}
/**
* Waits for a given key to be received from the console.
*
* @param key the key to wait for.
*/
public boolean waitForKey(char key) {
boolean isKey = false;
try {
// get key
isKey = Character.toLowerCase((char)System.in.read()) == key;
// clear input buffer
while (System.in.available() > 0) System.in.read();
} catch (IOException ioe) {
isKey = false;
}
return isKey;
}
/**
* Attempts to establish a socket connection to a given host on a given port.
*
* @param address the address of the host.
* @param port the port to scan on host.
* @return true if socket is open for communication.
*/
public static boolean doScan(InetAddress address, int port)
throws IOException {
Socket sock = null;
boolean success = false;
try {
// attempt to open a socket
sock = new Socket(address,port);
success = true;
} finally {
// always close the socket
if (sock != null) {
try {
sock.close();
} catch (IOException ioe) {
System.out.println("Error closing socket: " + ioe.getMessage());
}
}
}
return success;
}
/**
* Scans a range of ports on a given host, attempting to open socket connections.
*
* @param host the name of the host to scan.
* @param minport the minimum port number of the port range to scan.
* if <0, default to 1;
* @param maxport the maximum port number of the port range to scan.
* if <0, default to 1024;
* @param threads the number of concurrent threads to be used in scanning (1024 max).
* if <1 or greater than the number of ports to scan,
* defaults to the number of ports to scan (one thread each).
* @return an array of port numbers on with a socket was successfully connected.
* If no sucessful connections were made, an empty array is returned.
*/
public static Integer[] doScan(String host, int minport, int maxport, int threads) {
if (minport < 0) minport = 1;
if (maxport < 0) maxport = 1024;
if (threads < 1 || threads > maxport - minport + 1) threads = maxport - minport + 1;
if (threads > 1024) threads = 1024;
List ports = Collections.synchronizedList(new ArrayList());
InetAddress address;
Socket sock = null;
Scanner[] scanners = new Scanner[threads];
try {
// resolve the host address
address = InetAddress.getByName(host);
System.out.println("Scanning host: " + address);
// split the port range between threads
int chunk = (int)Math.ceil((maxport - minport + 1) / (double)threads);
int start;
int end;
for (int i = 0; i < threads; i++) {
start = minport + i * chunk;
end = Math.min(start + chunk - 1,maxport);
scanners[i] = new Scanner(ports,address,start,end);
scanners[i].start();
}
// wait for all threads to finish
for (int i = 0; i < threads; i++) {
synchronized (scanners[i]) {
while (!scanners[i].finished) {
try {
scanners[i].wait();
} catch (InterruptedException ie) {}
}
}
}
} catch (UnknownHostException uhe) {
System.out.println(uhe.getMessage());
}
return (Integer[])ports.toArray(new Integer[ports.size()]);
}
/**
* A Thread which scans a given port range.
*/
static private class Scanner extends Thread {
List ports;
InetAddress address;
int minport;
int maxport;
boolean finished;
/**
* Constructs a Scanner thread.
*
* @param ports a List to whom successfully scanned port numbers are added (as Integers).
* @param address the address of the host to scan.
* @param minport the minimum port number of the port range to scan.
* @param maxport the maximum port number of the port range to scan.
*/
public Scanner(List ports, InetAddress address, int minport, int maxport) {
this.ports = ports;
this.address = address;
this.minport = minport;
this.maxport = maxport;
this.finished = false;
System.out.println("Scanner initiated (" + minport + "-" + maxport + ")");
}
public void run() {
// loop through port range
for (int port = minport; port <= maxport; port++) {
try {
boolean success = doScan(address,port);
if (success) {
ports.add(new Integer(port));
System.out.println("Port " + port + " scan successful");
}
} catch (IOException ioe) {
System.out.println("Port " + port + " scan failed (" + ioe.getMessage() + ")");
}
Thread.yield(); // yield cpu time for better user response
}
// signal that the scan is finished
synchronized (this) {
finished = true;
this.notifyAll();
}
}
}
/**
* The main application entry point.
*/
public static void main(String[] args) {
try {
if (args.length < 1) {
System.out.println("Usage: java NetUtils [get|scan]\n\r");
} else if (args[0].equalsIgnoreCase("get")) {
if (args.length != 5) {
System.out.println("\n\rUsage: java NetUtils get <host> <port> <infile> <outfile>\n\r");
System.out.println("\t<host> the host to communicate with.");
System.out.println("\t<port> the port on which to communicate.");
System.out.println("\t<infile> a file containing data to send.");
System.out.println("\t<outfile> a file to output response to.");
} else {
doSession(args[1],
Integer.parseInt(args[2]),
new String[]{args[3]},
new String[]{args[4]}
);
}
} else if (args[0].equalsIgnoreCase("scan")) {
if (args.length < 2) {
System.out.println("\n\rUsage: java NetUtils scan <host> [minport] [maxport] [threads]\n\r");
System.out.println("\t<host> the address of the host to scan.");
System.out.println("\t[minport] the port to start scanning with (default 1).");
System.out.println("\t[maxport] the port to end scanning with (default 1024).");
System.out.println("\t[threads] the number of concurrent scanning theads to use (1024 max and default).");
} else {
String host = args[1];
int minport = args.length > 2 ? Integer.parseInt(args[2]) : -1;
int maxport = args.length > 3 ? Integer.parseInt(args[3]) : -1;
int threads = args.length > 4 ? Integer.parseInt(args[4]) : -1;
long start = System.currentTimeMillis();
Integer[] ports = doScan(host,minport,maxport,threads);
long end = System.currentTimeMillis();
System.out.println("Scanned ports " + minport + "-" + maxport + " on " + host + " in " + (end - start) + " milliseconds.");
System.out.println("\r\nSuccessfully connected to ports: " + Arrays.asList(ports));
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}