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:

192.168.15.73.64759

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

192.168.15.73

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 192.168.15.73.64759 | cut -d '.'  -f 1-4 
echo 192.168.15.73.64759 | sed -E 's,.[0-9]+$,,'

Or awk:

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

Use string substitution:

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

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 192.168.15.73.64759 | 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

in="192.168.15.73.64759"

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

~#: 192.168.15.73

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.