0

I am using netstat -lt | grep LISTEN to list all the tcp ports that are listening. I am supposed to use this data by my java application so I want to format the output in shell to reduce the processing overhead in Java. What I want is:

Protocol port status
tcp      4567 LISTEN

type of output. Is there any way to achieve this using netstat or is there any other network applications provided by unix to do this ?

I also tried reading the services files by:

less /etc/services | grep tcp | cut -d '#' -f 1

but that way it will list all the tcp ports even though they are open or not. Any suggestion would be great!

  • Do you care which IP it's listening on? For example a computer might be listening on 0.0.0.0:4567 which is completely different from listening on 127.0.0.1:4567 – David King Sep 19 '16 at 11:58
  • Actually I need this data for a client socket application, so yes the IP matters. – freerunner Sep 19 '16 at 12:03
2

Alternatively read the file /proc/net/tcp rather than deal with the security issues of running a shell program.

0

This doesn't include the column headers but it gives you the data you want in a tab delimited format

netstat -lnt | tail -n+3 | awk '{print $1 "\t" $4 "\t" $6}'

Running on my computer I get the following output

tcp     127.0.0.1:3306  LISTEN
tcp     0.0.0.0:22      LISTEN
tcp6    :::22   LISTEN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.