synking synking - 28 days ago 25
Java Question

java port scanner not working

I am taking a free online course for cybersecurity here https://cybersecuritybase.github.io/

Par of the course they want you to create a java port scanner they provide some of the code and you add the port scanner portion and i am having issues with it. Java is not a language i am really familiar with so i feel it's something simple but can't seem to figure it out.

code is here

package sec.portscanner;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.io.IOException;
public class PortScanner {

final static int MIN_PORT = 1024;
final static int MAX_PORT = 49151;

public static void main(String[] args) throws Exception {
Scanner reader = new Scanner(System.in);

System.out.println("Which address should I scan?");
String address = reader.nextLine();
System.out.println("Start at port?");
int start = Integer.parseInt(reader.nextLine());
System.out.println("End at port?");
int end = Integer.parseInt(reader.nextLine());

Set<Integer> ports = getAccessiblePorts(address, start, end);
System.out.println("");

if (ports.isEmpty()) {
System.out.println("None found :(");
} else {
System.out.println("Found:");
ports.stream().forEach(p -> System.out.println("\t" + p));
}
}

public static Set<Integer> getAccessiblePorts(String address, int start, int end) {
Set<Integer> accessiblePorts = new TreeSet<>();
start = Math.max(start, MIN_PORT);
end = Math.min(end, MAX_PORT);

for (int port = start; port <= end; port++)
{
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(address, port), 50000);
socket.close();
} catch(IOException e) {
System.out.println(e);
}
}

return accessiblePorts;
}
}


The portion I created is the for loop with the socket scan. It always prints out none found no matter what address i provide and i am not sure how to fix this. any pointers would be great I have searched and from what i see nothing is stand out wrong( at least i hope)

Answer

you are not adding to the accessiblePorts Set

try

Socket socket = new Socket();
socket.connect(new InetSocketAddress(address, port), 50000);
socket.close();
accessiblePorts.add (port);
Comments