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%,我还没成功过...
相关推荐
siriuuus18 分钟前
Nginx IP 透传
网络·nginx
缘友一世29 分钟前
漏洞扫描POC和web漏洞扫描工具
网络·安全·web安全
大海里的番茄31 分钟前
随时随地看监控:我的UptimeKuma远程访问改造记
linux·网络
ArabySide32 分钟前
【计算机网络】HTTP协议核心知识梳理
网络协议·计算机网络·http
christine-rr2 小时前
linux常用命令(6)——网络管理
linux·服务器·网络·ubuntu·网络安全
微信api接口介绍3 小时前
微信社群管理开发
java·开发语言·网络·微信
星哥说事4 小时前
网络设备配置:交换机、路由器OSPF和BGP、防火墙策略管理
网络·智能路由器
一只栖枝4 小时前
华为数通认证学习难吗?需掌握哪些核心知识点?
网络·智能路由器·华为认证·hcia·数通·考证·datacom
ARM+FPGA+AI工业主板定制专家4 小时前
【JETSON+FPGA+GMSL+AI】自动驾驶与移动机器人的摄像头如何实现高精度时间同步?
网络·人工智能·机器学习·fpga开发·cnn·自动驾驶
咕噜签名分发冰淇淋4 小时前
App中分发中的防盗链开发是做什么的?
运维·服务器·网络