java a program to print open ports

Solutions on MaxInterview for java a program to print open ports by the best coders in the world

showing results for - "java a program to print open ports"
Ivan
07 Jul 2019
1import java.io.IOException;
2import java.net.Socket;
3
4public class App {
5	public static void main(String[] args) {
6    	Socket tempSocket = new Socket();	//	Initialize
7        boolean isOpened;
8      	
9      	//	Loop through all the 65536 ports
10        for (int port = 0; port < 65536; port++) {
11          	//	We will assume the current port is opened unless
12          	//	An exception occurs
13            isOpened = true;
14          
15            try {
16              	//	Let's try connecting
17                tempSocket = new Socket("127.0.0.1", port);
18            }
19            catch (IOException e) {
20              	//	If an IOException occurs, then port is closed
21                isOpened = false;
22            }
23            finally {
24              	//	Close the socket to save resources
25                tempSocket.close();
26            }
27
28          	//	If port is opened print a message to the console
29            if (isOpened) {
30                String message = String.format("port %d is open", port);
31                System.out.println(message);
32            }
33        }
34    } 
35}