Python / iptables: original destination IP
I am trying to get the original destination information for packets forwarded with iptables (the ultimate goal is to redirect all network traffic to localhost while keeping the original destination IP address).
I am sending packages using the following code:
import socket HOST = '192.168.10.1' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send(b'whatever') s.close()
Then redirects it with:
iptables -t nat -A OUTPUT -d 192.168.10.1 -j DNAT --to 127.0.0.1
And then getting them with:
import socket
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
while True:
s.listen(5)
conn, addr = s.accept()
print('Connected by', addr)
data = conn.recv(1024)
if(data):
print(data)
conn.close()
I tried using something like
dst = conn.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST, 16)
but this leads to
AttributeError: 'module' object has no attribute 'SO_ORIGINAL_DST'
+3
user4960960
source
to share
1 answer
Some further readings and attempts led me to my error. I got a little confused with the various approaches I read about and lost track. The hint was to define SO_ORIGINAL_DST (in this case for TCP).
This code (taken from here ) does exactly what I want:
SO_ORIGINAL_DST = 80 sockaddr_in = conn.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16) (proto, port, a, b, c, d) = struct.unpack('!HHBBBB', sockaddr_in[:8]) print('Original destination was: %d.%d.%d.%d:%d' % (a, b, c, d, port))
+2
user4960960
source
to share