koch.trier
koch.trier

Reputation: 600

How to read tcp packets, which have been redirected to localhost?

I use iptables (PREROUTING) to redirect all TCP Traffic to a local port.

Now I want to capture these packets using a C program. I tried lots of socket variations (UDP / TCP / ...) but I cannot make a connection to localhost using the port I specified in iptables.

I can see all the packets being redirected, but how can I capture this traffic?

These are my rules (its Android, but should´t make any differences...):

Chain PREROUTING (policy ACCEPT 32 packets, 5675 bytes)
 pkts bytes target     prot opt in     out     source               destination
FIX ME! implement getprotobynumber() bionic/libc/bionic/stubs.c:384
    0     0 DNAT       tcp  --  any    any     anywhere             anywhere            tcp dpt:5512 to:192.168.1.107

Chain OUTPUT (policy ACCEPT 56 packets, 3433 bytes)
 pkts bytes target     prot opt in     out     source               destination
FIX ME! implement getprotobynumber() bionic/libc/bionic/stubs.c:384
    0     0 DNAT       tcp  --  any    any     anywhere             anywhere            tcp dpt:5512 to:127.0.0.1

I already tried creating TCP/UDP/RAW Socket (I also thought about "local" / UNIX-Sockets, but what´s the address for it?) and ServerSocket / DatagramServer - but I received nothing...

Thanks!!

Upvotes: 2

Views: 953

Answers (2)

Geoffrey
Geoffrey

Reputation: 11384

You could just use libpcap which will capture any traffic occurring on the ethernet device, and then just filter out what you want/need.

You cant make a connection to a port if there is no service listening on it, even with DNAT. You need to explain exactly what your trying to accomplish, explain your network setup and what data your trying to capture.

Upvotes: 1

sarnold
sarnold

Reputation: 104120

If you simply want to read the packets, then the ULOG target should probably be your first choice. You can configure netfilter to send packets to userspace, and the ulogd daemon can save the packets to a file or database, so presumably it can be configured or modified to send packets to your program directly.

If, on the other hand, you're trying to do some clever interpositioning to create a transparent VPN or something similar, ULOG would probably be a little too much work.

Upvotes: 0

Related Questions