Java TCP Socket Sniffing

2020-06-17 06:56发布

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?

7条回答
Bombasti
2楼-- · 2020-06-17 07:17

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楼-- · 2020-06-17 07:20

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).

查看更多
倾城 Initia
4楼-- · 2020-06-17 07:23

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

http://www.wireshark.org/

查看更多
不美不萌又怎样
5楼-- · 2020-06-17 07:27

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.

查看更多
来,给爷笑一个
6楼-- · 2020-06-17 07:36

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.

查看更多
▲ chillily
7楼-- · 2020-06-17 07:39

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.
查看更多
登录 后发表回答