简体   繁体   中英

Python/iptables: Original Destination IP

I'm trying to get original destination information for packets redirected with iptables (the ultimate goal is to redirect all network traffic to localhost while retaining the original destination ip).
I'm sending packets 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 redirecting it with:

iptables -t nat -A OUTPUT -d 192.168.10.1 -j DNAT --to 127.0.0.1

And then receiving 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 results in

AttributeError: 'module' object has no attribute 'SO_ORIGINAL_DST'

Some further reading and trying led me to my mistake. I got a little confused with various approaches I read about and lost track. The clue was in defining 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM