Python/iptables: Original Destination IP
Question: 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'
    


Answer: 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](https://github.com/apenwarr/sshuttle/blob/9ce2fa00f94c2f2e5c310abeb1a2907ae7e7a7b0/client.py))
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))
    

