Forem

Pavel Polívka
Pavel Polívka

Posted on

4 2

Logging unique IP addresses your Java code communicates with

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay