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 小时前
STM32F4+W5500 移植与开发常见问题
网络
qyr67892 小时前
全球新能源汽车电机驱动器市场深度调研报告
大数据·网络·人工智能·自动化·汽车
Hiyajo pray3 小时前
SDN 访问控制性能调优方法
服务器·网络·网络安全
初晴融雪-快雪时晴3 小时前
网络硬件全景梳理:从光纤到手机,一张网是如何连接的?
网络·智能手机·智能路由器
辣椒思密达4 小时前
AI出海产品本地化测试:住宅IP在模拟海外用户环境中的实践价值
网络协议·tcp/ip·安全·php·苹果vision pro
huainingning4 小时前
交换机通过ftp下载文件或者传输文件到ftp服务器
运维·服务器·网络
花生了什么事o6 小时前
DNS:把域名翻译成 IP 的层级查询机制
网络·网络协议·tcp/ip
海域云-罗鹏7 小时前
多云连接策略实战指南:企业如何打破云孤岛,构建跨公有云、私有云与混合云的高效网络
网络
其实防守也摸鱼7 小时前
渗透--损坏的对象级别鉴权漏洞(Broken Object Level Authorization, BOLA)
大数据·网络·数据库·学习·tcp/ip·安全·安全威胁分析
hehelm7 小时前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++