Asis Asis - 7 months ago 38
Bash Question

How to print the IP and the Port separately with netstat?

I want to print the IP and the Port separately using

netstat
command,

I tried this:

netstat -nat | awk '{print $4}'


But It gives me that:

192.168.1.213:40405


I want something like that:

First the IP:
192.168.1.213


and with another command the Port:
40405

Answer

If you want them as different commands, you could use sed to do it like:

netstat -nat | awk '{print $4}' | sed -e 's/:.*//' # gives IP only
netstat -nat | awk '{print $4}' | sed -e 's/.*://' # gives port only

Depending on how you're using it, you could store it in a bash variable and accomplish the same thing while access it like

both=$(netstat -nat | awk '{print $4}')
ip=${both%%:*}
port=${both##*:}