Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

run linux command in java  RSS feed

 
Bobes Calin
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello guys! I want to capture the output from the linux console. More precisely i want to capture the mac and the address from the /sbin/ifconfig -a command. I have made a method but it doesn`t work.



If i run xterm or an application it works. How can i run linux command and receive the output on java?

Cheers!
 
Carey Evans
Ranch Hand
Posts: 225
Debian Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The xterm command captures all of ifconfig’s output, and displays it in a window. To capture the output, you just want to run { "/sbin/ifconfig", "-a" }.

A couple of things, though:

  • If you have enough network interfaces, ifconfig will fill up its output buffer printing their details. Then your program will be waiting for it to exit, but it will be waiting for your program to read all its output, and neither will get anywhere. You need to read all the output before calling waitFor().
  • The NetworkInterface class may be all you need, depending on why you’re running ifconfig.
  •  
    Bobes Calin
    Greenhorn
    Posts: 22
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    thank you. Yes the { "/sbin/ifconfig", "-a" } and it show me only the fisrt line from the output. Can you please show me a good working example?

    Well i can see the mac address:



    but i can`t see the network ip. On windows work this code:



    in the first try is the localhost and the second should show me the network ip not 127.0.0.2 I don`t get it why? on windows work and on linux not, and that`s why i need to capture the cosole output for the ip.

    Cheers!
     
    Carey Evans
    Ranch Hand
    Posts: 225
    Debian Eclipse IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    InetAddress.getLocalHost() doesn't always work very well on Linux. In this case, I expect you have an entry in /etc/hosts for the name in /etc/hostname, with 127.0.0.2 as the IP address. If you call ni.getInetAddresses(), you can get all the network addresses.

    You can read all the output from ifconfig in a loop:

     
    Bobes Calin
    Greenhorn
    Posts: 22
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you Carey Evans!
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!