Search code examples
javanetworkingmonitor

How to monitor my network connection with Java?


Is there any sample code that can report the url that my PC is connecting with Java?

While I use my browser to connect to different sites and watch video online, it should capture the urls. Is it doable in Java?

I don't want detailed traffic, just record the urls.


Solution

  • The fastest way is probably going to be to capture the output of the command-line tshark program (for at least windows and linux). This works on my linux box:

    sudo tshark -f 'port 80' -R 'http' -V | grep -A 1 '^Hypertext Transfer Protocol'
    

    And produces output like:

    Running as user "root" and group "root". This could be dangerous.
    Capturing on eth0
    Hypertext Transfer Protocol
        GET /questions/4494294/r-gplots-barplots-how-to-fix-bar-width-independent-of-paper-setting HTTP/1.1\r\n
    --
    Hypertext Transfer Protocol
        HTTP/1.1 200 OK\r\n
    --
    Hypertext Transfer Protocol
        GET /posts/4494294/ivc/086e HTTP/1.1\r\n
    --
    Hypertext Transfer Protocol
        HTTP/1.1 204 No Content\r\n
    --
    Hypertext Transfer Protocol
        [truncated] GET /__utm.gif?utmwv=4.8.6&utmn=20455052&utmhn=stackoverflow.com&utmcs=UTF-8&utmsr=1600x1200&utmsc=24-bit&utmul=en-us&utmje=1&utmfl=10.1%20r102&utmdt=graph%20-%20R%3A%20gplots%2C%20barplots%3A%20how%20to%20fix%20bar%20width%20i
    --
    Hypertext Transfer Protocol
        HTTP/1.1 200 OK\r\n
    --
    

    You should get something similar for Windows. Experiment. How you get the output of tshark into java is up to you.

    If you want an all-java solution, how about http://jnetpcap.com/ ?

    You're going to have to write (or use a library that provides) some platform specific JNI code.

    libpcap/WinPcap that jNetPcap uses provides this reliably on at least Windows and Linux from my experience. I have experience with libpcap/WinPcap but not with jNetPcap.

    tshark also uses libpcap/WinPcap actually.

    Either way, you're going to see very many false positives. Opening a HTML page requires getting many, many images, style sheets, javascript libraries etc. The snippet above is from opening a stackoverflow.com page.