我正在尝试将一些数据发送到本地地址,然后使用特定接口(interface) ppp0
将其“转发”到外部地址。我认为我的问题与数据包路由/套接字绑定(bind)问题有关,但我是一个新手,无法理解它。
我的网络设置:
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 wlan0
0.0.0.0 192.168.1.1 0.0.0.0 UG 303 0 0 wlan0
10.64.64.64 0.0.0.0 255.255.255.255 UH 0 0 0 ppp0
169.254.0.0 0.0.0.0 255.255.0.0 U 304 0 0 wwan0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 wlan0
192.168.1.0 0.0.0.0 255.255.255.0 U 303 0 0 wlan0
使用环回:
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
在 Python 端,我绑定(bind)套接字
HOST = ''
PORT_vid = 0
try:
s_vid = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s_vid.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s_vid.setsockopt(socket.SOL_SOCKET, 25, "ppp0")#this works to bind it to ppp0
print("Socket created.")
except socket.error, msg:
print("Failed. Error: " + str(msg))
sys.exit()
try:
s_vid.bind((HOST,PORT_vid))
print("Socket binding complete.")
except socket.error, msg:
print("Bind failed. Error: " + str(msg))
s_vid.close()
sys.exit()
如果我尝试简单地 ping 一个外部地址,效果很好。现在我使用 netcat
#p_nc is taking some data from a local process and sending it to the local point
p_nc = subprocess.Popen(["nc", "-u", "127.0.0.1", str(s_vid.getsockname()[1])],stdin=another_process.stdout)
然后我在那个本地端口上监听并转发它(我有充分的理由不使用 netcat
发送它)
while 1:
data, addr = s_vid.recvfrom(1024)
print('local reception')
#do stuff here with 'data' - never reached
s_vid.sendto(data_amended,(external_ip,external_port))
数据必须通过 ppp0
到达外部地址,并且最好使用“process to netcat
to local to external”设置(如上所述)。 s_vid
套接字不需要监听任何外部流量,它只是发送外部流量并在本地监听。
我猜我的套接字绑定(bind)到 ppp0
,因此无法读取环回数据,但我不知道如何修复它。 Python 端或 ip 路由端的解决方案都可以,但我是路由和接口(interface)的新手。
最佳答案
最后只是在我的代码中添加了一个新套接字,它绑定(bind)到 lo
接口(interface)(类似于另一个绑定(bind)到 ppp0
的方式)。 lo
套接字读取本地套接字(循环中的 s_lo.recvfrom()
),而我们保留 s_vid.sendto()
。
关于python - linux环回接口(interface)到python中的特定接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46434722/