TCP打孔问题 [英] Problems with TCP hole punching
问题描述
我尝试使用 这篇文章.但是,我无法连接任何东西.代码如下:
I've tried to write a basic TCP hole puncher for a firewall in Python 3 using the principles outlined in this article. I'm having trouble getting anything to connect, though. Here is the code:
#!/usr/bin/python3
import sys
import socket
import _thread as thread
def client():
c = socket.socket()
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
c.bind((socket.gethostbyname(socket.gethostname()), int(sys.argv[3])))
while(c.connect_ex((sys.argv[1], int(sys.argv[2])))):
pass
print("connected!")
thread.interrupt_main()
def server():
c = socket.socket()
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
c.bind((socket.gethostbyname(socket.gethostname()), int(sys.argv[3])))
c.listen(5)
c.accept()
print("connected!")
thread.interrupt_main()
def main():
thread.start_new_thread(client, ())
thread.start_new_thread(server, ())
while True:
pass
if __name__ == '__main__':
main()
我决定在我的本地机器上尝试打孔器,以便我可以捕获两个实例发送的所有流量.我先设置了一个环回防火墙:
I decided to try the puncher on my local machine, so that I could capture all the traffic sent by both instances. I first set up a loopback firewall:
iptables -A INPUT -i lo -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i lo -j DROP
然后我启动了脚本的两个副本:
Then I launched two copies of the script:
left$ ./tcphole.py localhost 20012 20011
和
right$ ./tcphole.py localhost 20011 20012
根据 Wireshark,我可以看到 SYN 数据包正在双向传输:
I can see according to Wireshark that the SYN packets are being transmitted both ways:
但没有打印连接!"我做错了什么?
But nothing ever prints "connected!" What am I doing wrong?
推荐答案
事实证明答案非常简单:如果数据包没有进入RELATED
相同的 IP 地址!
The answer turned out to be quite simple: packets aren't considered RELATED
if they aren't coming to the same IP address!
将 bind
行更改为
c.bind('', int(sys.argv[3])))
(''
绑定到环回地址)完全解决了这个问题.
(the ''
binds to the loopback address) fixes the problem entirely.
这篇关于TCP打孔问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!