简体   繁体   English

Python / iptables:原始目标IP

[英]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). 我正在尝试获取使用iptables重定向的数据包的原始目标信息(最终目标是将所有网络流量重定向到localhost,同时保留原始目标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). 线索是定义SO_ORIGINAL_DST(在本例中为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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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