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%,我还没成功过...
相关推荐
dldw77743 分钟前
IE无法正常登录windows2000server的FTP服务器
运维·服务器·网络
运维有小邓@1 小时前
什么是重放攻击?如何避免成为受害者?
运维·网络·安全
光路科技1 小时前
工业数字化三大核心概念拆解:IIoT、工业互联网与工业4.0
网络
汤愈韬2 小时前
下一代防火墙通用原理
运维·服务器·网络·security
有代理ip4 小时前
网络隐私防护指南:代理服务与换 IP 工具的科学结合
网络·tcp/ip·web安全
不是书本的小明4 小时前
阿里云专有云网络架构
网络·阿里云·架构
mounter6255 小时前
【内核前沿】从 veth 到 netkit:深度解析 TCP devmem 穿透容器屏障的“队列租赁”黑科技
网络·ebpf·linux kernel·devmem tcp·netkit·队列租赁
yleihj5 小时前
vCenter计算机SSL证书续期
服务器·网络协议·ssl
lifewange5 小时前
https和http有什么区别
网络协议·http·https
爱学习的小囧6 小时前
vSphere Supervisor 服务配置指南:自签名容器注册表使用教程
服务器·网络·esxi·虚拟化·vcf