Java TCP Socket Sniffing

2020-06-17 06:41发布

问题:

I am using TCP sockets to communicate data between a server and client program using a specific port number on the same computer (localhost).

I need a software that can capture the data being sent/received through that socket?

(or)

What's the simplest way of sniffing packets from a specified port in Java?

回答1:

I suggest using Wireshark. It's easy to use and runs on many platforms.

http://www.wireshark.org/



回答2:

If you are up to some coding (and not just running the wireshark/tcpdump) then you have few choices. If you want stick to Java, then the only (?) option to use raw sockets is via JNI and there are few libraries that can help, for example:

  • jNetPcap - wrapper around the native libpcap/winpcap libraries, exposing all of their functions and structures
  • RockSaw - API for using raw sockets


回答3:

The easiest way is to replace the InputStream/OutputStream from a socket in one of the programs with a proxy implementation, that either prints/logs or "tees" to the original and a print/log stream.

But there's plenty of sniffers out there if you really want to get messy.



回答4:

If you don't mind getting down and dirty with the command line you could try netcat. It'll let you listen on a port and dump the output to a file if you like.
You can also make it send fake data and record the response.

I often use it as a pretend HTTP proxy (and configure Firefox to use it) to discover what is being sent over the wire.



回答5:

Tcpdump can also be used directly, if the volume of traffic is not high, obviating the need to use wireshark. Just something like

tcpdump -ni lo0 port 1234

should be all you need (lo0 is the loopback interface on all Unix/Linux systems; also change the port number of course).



回答6:

Run your program like so:

java -Djavax.net.debug=all helloworld.java

The switch is fully documented on the Oracle JSSE page

Pros:

  • Much simpler than other suggested solutions (requires no external software)
  • Can also decrypt/dump TLS/SSL connections :)

Cons:

  • This will only work if you are using classes from java.net.* e.g. OutputStream or InputStream This will not work if you're using raw sockets. This is documented in the link.
  • Believe this may only work on the Oracle JDK.


回答7:

You can use tcpdump that gives you a variety of options. You save the capture in a .pcap file with the -w option and when you are done you open that file with wireshark. The advantage of this way is that you can capture a high rate of packets per second without affecting the overall performance of your pc (even if it is low end).