1
final String commands[] =  {"arp", "-n", "|" ,"grep", "98:5d:ad:3d:36:ef", "|", "awk '", "{print $1}", "'"};
ProcessBuilder pb = new ProcessBuilder(commands); 

I would like to retrieve the IP, given the MAC ADDRESS.
When I insert this command to the terminal (ubuntu 16.04) it works.
But it doesn't work when I use it in JAVA.

What am i doing wrong?

It only works when I run it like this:

final String commands[] =  {"arp", "-n"};
ProcessBuilder pb = new ProcessBuilder(commands); 
Daniel Puiu
  • 962
  • 6
  • 21
  • 29
  • I only get this: exit: 255 – Vyasa R. Ituarte Correa Jun 11 '18 at 17:44
  • @Daniele's answer is correct - the reason is that your Java code doesn't provide shell features, such as piping the output of one command to the next. – schneida Jun 11 '18 at 21:59
  • Near dupe https://stackoverflow.com/questions/31776546/why-does-runtime-execstring-work-for-some-but-not-all-commands and https://stackoverflow.com/questions/49223605/using-ssmtp-and-processbuilder (`ProcessBuilder` and `Runtime.exec` are alike in this respect, although they have other differences) – dave_thompson_085 Jun 12 '18 at 02:43

1 Answers1

2

You need to invoke "sh" and pass to that program your piped command. Try:

ProcessBuilder b = new ProcessBuilder( "/bin/sh", "-c",
               "arp -n | grep 98:5d:ad:3d:36:ef | awk '{print $1}'" );
Daniele
  • 2,672
  • 1
  • 14
  • 20
  • Or just run `"arp","-n"` and use `String.contains` or `String.indexOf` to replace the `grep` and `String.split` or `Scanner` or `StringTokenizer` to replace the `awk $1` – dave_thompson_085 Jun 12 '18 at 02:46