loading...

Logging unique IP addresses your Java code communicates with

pavel_polivka profile image Pavel Polívka ・2 min read

Recently I needed some utility that would log all unique IP addresses all the Java processes on a server communicated with.

I googled a bit and did not discovered nice and easy solution for this. So I decided to do some bash-fu and wrote the following script.

while true
do
    netstat -nput 2>/dev/null | grep 'java' | tr -s ' ' | cut -f5 -d ' ' | cut -f1 -d ':' | uniq | while read -r ip; do grep -qxF $ip ip.log || echo $ip >> ip.log; done
    sleep 5
done

Let's go over it step by step to explain what it does:

  • while true - this means that when executed it will run until stopped, easy
  • netstat -nputw 2>/dev/null - netstat prints network connections
    • -n - show numerical address instead of trying to resolve host names
    • -p - show PID of the program
    • -u - include UDP connections
    • -t - include TCP connections
  • grep 'java' - only take those lines that have Java in them (PID contains java for Java apps)
  • tr -s ' ' - replaces each sequence of spaces with a single space
  • cut -f5 -d ' ' - takes fifth column (separated by spaces)
  • cut -f1 -d ':' - takes first part (separated by :) - removes port
  • uniq - makes the list unique
  • while read -r ip; do grep -qxF $ip ip.log || echo $ip >> ip.log; done - adds it to a log file if it does not contain it already
    • grep -qxF
      • -q - quiet, do not write anything to standard output
      • -x - select only those matches that exactly match the whole line
      • -F - interpret PATTERNS as fixed strings

Hope this will help you or if you have a better solution please let me know.


You can follow me on Twitter to get more awesome content like this.

Posted on by:

pavel_polivka profile

Pavel Polívka

@pavel_polivka

Father, developer, bad sci-fi writer, love to learn stuff

Discussion

pic
Editor guide