Skip to content

Instantly share code, notes, and snippets.

@imba-tjd
Created October 19, 2024 11:56
Show Gist options
  • Save imba-tjd/02a42eae4791c66beb5af447888136a4 to your computer and use it in GitHub Desktop.
Save imba-tjd/02a42eae4791c66beb5af447888136a4 to your computer and use it in GitHub Desktop.
udp hole punching
# 当两台电脑都有公网IP,却无法访问时,可能是被防火墙拦截了。inbound filter只允许内部往外部建立连接。
# 想到普通家宽,建立连接后,双方是可以互发消息的,证明网络是通的。而UDP是无连接的,怎么做到收回复呢?
# 其实防火墙的原理是检测发出去的五元组,遇到对应的回复就放行传入。
# 从实践上来说,只要双方互发消息,就可以了。这就是“打洞”
import socket, time, sys, threading
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.bind(('::', int(sys.argv[1])))
target = (sys.argv[2], int(sys.argv[3]))
def send():
while True:
s.sendto(b'ok', target)
time.sleep(1)
threading.Thread(target=send, daemon=True).start()
while True:
msg, addr = s.recvfrom(99)
print(msg)
# 运行:
# 电脑A:python udphp.py A绑定的端口 B的IP B的端口
# 电脑B:python udphp.py B绑定的端口 A的IP A的端口
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment