Search code examples
androidifconfig

ifconfig works in linux terminal but it does not work in my app


I have an android phone. It's rooted. I am trying to run ifconfig command. it works in Linux Terminal, but not works in Android Java Coding.

Environment

Android Version: android 10

Status: rooted

It works in Linux Terminal

I downloaded a Linux terminal in the Google App Store. I opened it, and running:

$ ifconfig

it lists a list of information that I need. it works perfectly.

It does not work in Android Java Coding

But when I type the same command in the Android app. it does not work. It shows nothing. bellow is the code that I ran:

            // Executes the command.
            Process process = Runtime.getRuntime().exec("/system/bin/ifconfig");

            // Reads stdout.
            // NOTE: You can write to stdin of the command using
            //       process.getOutputStream().
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            int read;
            char[] buffer = new char[4096];
            StringBuffer output = new StringBuffer();
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            reader.close();

            // Waits for the command to finish.
            process.waitFor();

            return output.toString();

I copied those codes from Run native executable code in android

Questions

Why it does not work in java code? Is there anything else I missed?


Solution

  • Thanks @Erlkoenig mentions. I ran it with su grant permission.

    bellow is my changed code:

                // Executes the command.
                Process process = Runtime.getRuntime().exec("su");
    
                // Writes stdin
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(process.getOutputStream()));
                String command = "/system/bin/ifconfig";
                writer.write(command.toCharArray());
                writer.flush();
                writer.close();
    
                // Reads stdout.
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));
                int read;
                char[] buffer = new char[4096];
                StringBuffer output = new StringBuffer();
                while ((read = reader.read(buffer)) > 0) {
                    output.append(buffer, 0, read);
                }
                reader.close();
    
                // Waits for the command to finish.
                process.waitFor();
    
                return output.toString();
    

    remember to close writer, after had written the command into stdin.