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%,我还没成功过...
相关推荐
zizisuo2 分钟前
面试篇:Spring Security
网络·数据库·安全
玉笥寻珍3 分钟前
Web安全渗透测试基础知识之HTTP参数污染篇
网络·网络协议·安全·web安全·http
GCKJ_082442 分钟前
观成科技:加密C2框架Vshell流量分析
网络·科技·信息与通信
玉笥寻珍2 小时前
Web安全渗测试基础知识之SSL交互异常利用篇
网络协议·安全·web安全·网络安全·交互·ssl
大蚂蚁2号2 小时前
windows文件共享另一台电脑资源管理器网络文件夹无法找到机器
运维·服务器·网络
LetsonH3 小时前
Home Assistant 米家集成:开启智能家居新体验
网络·智能家居
欧先生^_^3 小时前
Docker 的各种网络模式
网络·docker·容器
what_20183 小时前
分布式2(限流算法、分布式一致性算法、Zookeeper )
分布式·网络协议·rpc
彬彬醤3 小时前
查询电脑伪装IP,网络安全速查攻略!
网络·网络协议·tcp/ip·安全·web安全·http·https
还有几根头发呀5 小时前
常见 RPC 协议类别对比
网络协议