udp穿透的方法

服务端缓存客户端ip+端口信息,如果有新的客户端连接上来返回给对方。

server

python 复制代码
import socket

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind(("0.0.0.0", 2023))
    cache = {}
    while True:
        packet = udp_socket.recvfrom(2048)
        current = packet[1]
        key = packet[0].decode("utf-8")
        print("recvfrom key:", key)
        if key not in cache:
            cache[key] = packet[1]
            print("pending:", current)
        else:
            last = cache[key]
            udp_socket.sendto((current[0] + ":" + str(current[1])).encode("utf-8"), last)
            udp_socket.sendto((last[0] + ":" + str(last[1])).encode("utf-8"), current)
            del cache[key]
            print("done:", last, current)

    udp_socket.close()


if __name__ == "__main__":
    main()

客户端先请求服务端,请求后获取p2p的地址,然后开始周期echo。

client

python 复制代码
import socket
import sys
import time

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.settimeout(10)
    server = (u"192.168.3.20",2023)
    key = u"----uni-key-yeshen----"
    this_client = sys.platform + str(time.time())

    udp_socket.sendto(key.encode("utf-8"), server)
    print("waiting..")
    packet = udp_socket.recvfrom(2048)
    print("packet",packet)
    peer = packet[0].split(":")
    target_peer = (peer[0],int(peer[1]))

    while True:
        udp_socket.sendto(this_client.encode("utf-8"), target_peer)
        print("peer send",this_client,target_peer)
        msg = udp_socket.recvfrom(2048)
        print("peer recv",msg)
        time.sleep(1)

    udp_socket.close()


if __name__ == "__main__":
    main()

自测效果:

  1. 在服务端上开启,两个客户端都在同一个局域网里面,有70%左右的概率连通(10个端口,有7个能成功)。数据和wifi都是这样。
  2. 一个设备在wifi、一个在数据上,连通的概率大约是0%,我还没成功过...
相关推荐
蜡笔小新星11 分钟前
Python Kivy库学习路线
开发语言·网络·经验分享·python·学习
小白爱电脑2 小时前
WIFI网速不够是不是光猫的“路由模式”和“桥接模式”配置错了?
网络·智能路由器·桥接模式
仍有未知等待探索2 小时前
Linux 传输层UDP
linux·运维·udp
qxqxa3 小时前
cfg80211是怎么配置无线设备的AP的?
网络·驱动开发
秋夫人4 小时前
http cache-control
网络·网络协议·http
不灭锦鲤6 小时前
ssrf学习(ctfhub靶场)
网络·学习·安全
weixin_548444266 小时前
2024年最新版本神马TV8.5影视APP源码 293TV影视点播系统源码搭建教程 神马TV8.2加强版反编译教程 保姆级小白可搭建 完整版本视频教程
网络
网络研究院8 小时前
如何安全地大规模部署 GenAI 应用程序
网络·人工智能·安全·ai·部署·观点
limengshi1383928 小时前
通信工程学习:什么是RIP路由信息协议
网络·网络协议·学习·智能路由器·信息与通信
GodK7779 小时前
HTTPS 的加密流程
网络协议·http·https