In this example you’ll see how to create a simple port scanner program to check the open ports for the specified host name.
package org.kodejava.net;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class PortScanner {
public static void main(String[] args) throws Exception {
String host = "localhost";
InetAddress inetAddress = InetAddress.getByName(host);
String hostName = inetAddress.getHostName();
for (int port = 0; port <= 65535; port++) {
try {
Socket socket = new Socket(hostName, port);
String text = hostName + " is listening on port " + port;
System.out.println(text);
socket.close();
} catch (IOException e) {
// empty catch block
}
}
}
}
The result of the code snippet above are:
localhost is listening on port 21
localhost is listening on port 80
localhost is listening on port 135
localhost is listening on port 445
localhost is listening on port 3000
...
...
localhost is listening on port 63342
localhost is listening on port 63467
localhost is listening on port 64891
localhost is listening on port 64921
localhost is listening on port 65001
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024