3

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();
    }
}



} 
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
Stelios Savva
  • 812
  • 1
  • 10
  • 30
  • This might be a bit duplicate to http://stackoverflow.com/questions/3159913/problem-reading-inputstream-from-java-process-runtime-getruntime-exec-or-pr – Wolfgang Fahl Oct 21 '12 at 17:47
  • Have you run the command to make sure it produces output? – daniel gratzer Oct 21 '12 at 17:49
  • @WolfgangFahl i researched the question you posted prior to posting my question, but it seemed too complicated working with the thread and cause i haven't been familiar with ProcessBuilder. Thanks for pointing it out though. – Stelios Savva Oct 22 '12 at 13:25
  • @jozefg Yes, the command produces the correct output in the terminal – Stelios Savva Oct 22 '12 at 13:25

1 Answers1

2

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..
Mik378
  • 21,881
  • 15
  • 82
  • 180