Search code examples
javaterminalifconfigoutput

Reading the output of a terminal command in java with BufferedReader


Noobie at java just starting, would appreciate any help. So my code is this and for some reason I cant get the output to work..I ve been sitting at this for hours..

package askisi1;

import java.net.*;
import java.util.*;
import java.lang.*;
import java.io.*;


public class Main{

public static void main(String[] args){

    try{

        String command = "ifconfig eth1 | grep -oP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'";
        Process child = Runtime.getRuntime().exec(command);

        System.out.println("So far so good");
        BufferedReader r = new BufferedReader(new InputStreamReader(child.getInputStream()));
        String s;
        while ((s = r.readLine()) != null) {
        System.out.println(s);
        }
        r.close();
        System.out.println("Continue..");
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}



} 

Solution

  • Runtime.exec() needs some additional information to execute an Unix Command.

    So, assuming my ethernet card is lo0:

    String[] command = {
                        "/bin/sh",
                        "-c",
                        "ifconfig lo0 | grep -oP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'"
                }; 
    Process child = Runtime.getRuntime().exec(command);
    // following here your remaining unchanged code
    

    This prints:

    So far so good
    127.0.0.1
    Continue..