Home » Java programming language

Java SecurityManager checkListen() method with example

SecurityManager Class checkListen() method: Here, we are going to learn about the checkListen() method of SecurityManager Class with its syntax and example.
Submitted by Preeti Jain, on December 16, 2019

SecurityManager Class checkListen() method

  • checkListen() method is available in java.lang package.
  • checkListen() method invokes checkPermission with the given SocketPermission("localhost:"+port_no,"listen") when the given argument value is not equal to 0 otherwise it invokes checkPermission with the SocketPermission("localhost:1024-","listen") when the given argument value equal to 0.
  • checkListen() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • checkListen() method may throw an exception at the time of establishing the connection.
    SecurityException – This exception may throw when the calling thread is not allowed to listen (i.e. it does not wait for a connection request) on the given port.

Syntax:

    public void checkListen(int port_no);

Parameter(s):

  • int port_no – represents the local port number.

Return value:

The return type of this method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void checkListen(int port_no)
// method of SecurityManager 

public class CheckListen extends SecurityManager {
    // override checkListen() of SecurityManager
    public void checkListen(int port_no) {
        throw new SecurityException("No such port exists!!!!");
    }

    public static void main(String[] args) {
        int port_no = 8090;

        // By using setProperty() method is to set the policy property 
        // with security manager
        System.setProperty("java.security.policy", "file:/C:/java.policy");

        // Instantiating a CheckListen object
        CheckListen cl = new CheckListen();

        // By using setSecurityManager() method is to set the
        // security manager
        System.setSecurityManager(cl);

        // By using checkListen(8090) method is to check
        // port number 
        cl.checkListen(8090);

        // Display the message
        System.out.println("Not Restricted..");
    }
}

Output

Exception in thread "main" java.lang.SecurityException: No such port exists!!!!
	at CheckListen.checkListen(CheckListen.java:8)
	at CheckListen.main(CheckListen.java:27)



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.