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%,我还没成功过...
相关推荐
黎茗Dawn24 分钟前
5.子网划分及分片相关计算
网络·智能路由器
恰薯条的屑海鸥37 分钟前
零基础在实践中学习网络安全-皮卡丘靶场(第十四期-XXE模块)
网络·学习·安全·web安全·渗透测试
科技小E38 分钟前
口罩佩戴检测算法AI智能分析网关V4工厂/工业等多场景守护公共卫生安全
网络·人工智能
御承扬1 小时前
从零开始开发纯血鸿蒙应用之网络检测
网络·华为·harmonyos
DevSecOps选型指南9 小时前
2025软件供应链安全最佳实践︱证券DevSecOps下供应链与开源治理实践
网络·安全·web安全·开源·代码审计·软件供应链安全
利刃大大10 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
国科安芯10 小时前
抗辐照MCU在卫星载荷电机控制器中的实践探索
网络·嵌入式硬件·硬件工程·智能硬件·空间计算
EasyDSS12 小时前
国标GB28181设备管理软件EasyGBS远程视频监控方案助力高效安全运营
网络·人工智能
玩转4G物联网12 小时前
零基础玩转物联网-串口转以太网模块如何快速实现与TCP服务器通信
服务器·网络·物联网·网络协议·tcp/ip·http·fs100p
派阿喵搞电子12 小时前
Ubuntu下有关UDP网络通信的指令
linux·服务器·网络