bailey_f
bailey_f

Reputation: 11

Java Socket Packet Interception

I'm trying to write a socket program in Java that intercepts data/packets.

I've successfully written this in python:

import socket

def createListener(port):
    srvSock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
    srvSock.bind(('localhost', port))
    srvSock.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
    while True:
        raw_data, addr = srvSock.recvfrom(65536)
        print('data: ' , raw_data)

createListener(80)

This is my basic Java socket program

public static void main(String[] args) {
        try{
            ServerSocket ss = new ServerSocket(80);
            Socket s = ss.accept();
            DataInputStream dis = new DataInputStream(s.getInputStream());
            String str = (String)dis.readUTF();
            System.out.println("data: "+str);
            ss.close();
        } catch(IOException i){
            System.out.println(i);
        }

    }

However, when run, it doesn't intercept all data moving through the port on the network like the python program does. Specifically this line srvSock.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) in the Python script enables the socket to listen to the port and capture/intercept the entirety of the data going through it.

I cannot find a Java alternative to this syntax or any solution to my problem at all for that matter. I would appreciate any help in how to use sockets to intercept packets on a network port.

Thanks

Upvotes: 1

Views: 772

Answers (2)

Yurowitz
Yurowitz

Reputation: 1396

From the looks of it, you're trying to read incoming bytearrays as string lines. If that is so, this is what I do to read lines without missing a single line (In Kotlin):

   socket.getInputStream().bufferedReader(Charsets.UTF_8).forEachLine {
       it -> { /* Do what you wanna do with the input */ }
   }

In Java, it's much less abstract :

   BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8), 8 * 1024) 

Then, use lines from this buffered reader as a line sequence to read your incoming lines.

Upvotes: 0

thetechnician94
thetechnician94

Reputation: 545

Im fairly certain what you are trying to do cannot be done with Java. It looks like you are trying to use "promiscuous mode", but Java sockets cannot be started in promiscuous mode. Java sockets are an end-to-end implementation: they can't listen on the network port for all traffic. For sure the network port would have to be in promiscuous mode, but I don't think Java is the right choice for you.

The only thing I can think of that might get you there would be doing a native call in something like JNI, but I wouldn't even really know where to start with that.

Here is a really old post that I found that is kind of related: java socket and web programing

Upvotes: 1

Related Questions