Extracting IP from IP.port

I’ve done a lot of digging but haven’t found an answer to my problem.

Currently, I have the following command:

netstat | grep telnet | grep ESTABLISHED | awk 'NR==1{ print $5}'

Which returns something like this:

From this, I want to get just the IP without the port. So,

The system I’m doing this on runs an embedded Unix variant (QNX) and does not support -o as an option to grep. The system supports sed which is likely the best route, but I’m unfamiliar with that application.

Can anyone tell me what I could add to get the output I’m looking for?

Asked By: Trey


You could use cut or sed:

echo | cut -d '.'  -f 1-4 
echo | sed -E 's,.[0-9]+$,,'

Or awk:

echo | awk -F '.' '{print $1"."$2"."$3"."$4}'
Answered By: Arkadiusz Drabczyk

Use string substitution:

$ IP=
$ echo ${IP%.*}

IP=$(netstat | grep telnet | grep ESTABLISHED | awk 'NR==1{ print $5}')
echo ${IP%.*}
Answered By: Ravexina

Having just learned about ss:

ss -n -o state established '( dport = :telnet or sport = :ssh )' | 
  awk  'NR==2 { print substr($5, 1, index($5, ":")-1) }'

I use NR==2 to skip past the header and grab only the first line of output, to corresponding with your netstat/grep behavior. The rest of the awk code prints $5, but starting from the first character and only going until the index where “:” is found, minus one.

If the system is missing ss, then you can use sed:

echo | sed 's/.[0-9]*$//'

netstat | grep telnet | grep ESTABLISHED | awk 'NR==1{ print $5}' | sed 's/.[0-9]*$//'

This replaces “period followed by zero or more digits followed by the end of the line” with “nothing”.

Answered By: Jeff Schaller
netstat | grep telnet | grep ESTABLISHED | awk 'NR==1{ print $5}' |grep -Po "b(?:d{1,3}.){3}d{1,3}b"
Answered By: Emilio Galarraga

You can also do that using grep -E


echo $in | grep -Eo "([[:digit:]]{1,3}.){4}" | grep -Po "(.*)(?=.$)"


the -E allows extended regex, and -P for Perl compatible to include the last dot in the pattern but excluding it from the output

Answered By: Chen A.

Applying a single awk command to the output of netstat would be enough to capture any line that contains the sub-strings ESTABLISHED and telnet and then output a trimmed 5th field.

netstat | awk '/ESTABLISHED/ && /telnet/ { sub(/.[^.]+$/,"",$5); print $5 }'

If you need only the first result, change print $5 to print $5; exit in the awk code, or pass it through head -n 1.

Answered By: Kusalananda
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.