Search code examples
javacommandfirewallwindows-firewallnetsh

Java code to check the status of firewall


I'm building a Java application to check to status of firewall. In simpler words,it should give the output whether the firewall is ON or OFF(note that when i say firewall ,i mean the built-in firewall that comes with Windows OS). I need this code to give the status of the local machine itself. Basically ,what i'm trying to do is simulate the command "netsh advfirewall show allprofiles state".


Solution

  • As far as I know there are no Java APIs for checking the built in Windows firewall status, so you will probably have to resort to executing a shell command from Java. An example:

    StringBuilder output = new StringBuilder();
    Process p = Runtime.getRuntime().exec("netsh advfirewall show allprofiles state");
    p.waitFor(); //Wait for the process to finish before continuing the Java program.
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = "";           
    while ((line = reader.readLine()) != null) {
      output.append(line + "\n");
    }
    //output.toString() will contain the result of "netsh advfirewall show all profiles state"
    

    As I do not have a Windows machine at hand I do not know what netsh advfirewall show allprofiles state returns but I imagine that a simple output.toString().contains() will work. Do not forget to catch any exceptions!