Search code examples
javasocketstcpudpip

Read IP-layer headers using Java sockets


Is there a way (in Java) to read IP-layer headers (I'm interested in src & dst IPs), using TCP or UDP socket?

I know it's possible using pcap (packet capture), but I didn't find a way to do it using sockets. What's the reason behind that?


Solution

  • At the operating system level, you need raw sockets to access IP-layer headers. But fortunately raw sockets don't exist in pure Java so you need native code to make the relevant syscalls.

    There are Java libraries that use a JNI component for the native calls. One example (which I used successfully in the past) is Rocksaw.