#!/bin/sh
# $Id: reverse_replace.sh 9 2015-02-20 20:56:07Z jo $
#
# Usage e.g.: netstat -n -4 | reverse_replace.sh 
# Parses stdin for IP4 addresses and replaces them 
# with names retrieved by reverse_dns.sh
#
# This has been tested on debian and asuswrt. Plese
# report successful tests on other platforms.
#
# Author: Joachim Zobel <jz-2014@heute-morgen.de>
# License: Consider this MIT style licensed. You can 
#   do as you ike, but you must not remove my name.
#

DIR=`dirname $0`
DNS=$DIR/reverse_dns.sh

# sed regex
IP_regex='[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'

while read LINE; do
  for IP in `echo "$LINE" | \
              sed "s#\b\($IP_regex\)\b#\n\1\n#g" | \
              grep $IP_regex ` 
  do
    NAME=`$DNS $IP`
    LINE=`echo "$LINE" | sed "s#$IP#$NAME#" ` 
  done
  echo $LINE
done

