多个 programs/instances 在 C# 中使用相同的 UDP 端口

Multible programs/instances using the same UDP Port in C#

我正在为一些网络魔法而苦苦挣扎,希望有人能够向我解释发生了什么。

我正在尝试重用 udp 端口​​。因此,如果我有多个程序在同一个 udp 端口​​上侦听,我希望两个应用程序都能接收由不同设备发送的数据。

使用下面的代码我能够实现:

            IPEndPoint localEndoint = new IPEndPoint(IPAddress.Any, 67);    //the local endpoint used to listen to port 67
            //Create a new UDP Client and bind it to port 67
            DhcpSniffer = new UdpClient();
            DhcpSniffer.ExclusiveAddressUse = false;    //Allow multible clients to connect to the same socket
            DhcpSniffer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // Connect even if socket/port is in use
            DhcpSniffer.Client.Bind(localEndoint);
            DhcpSniffer.Client.ReceiveTimeout = Timeout;
            //receive on port 67 
            dhcpPacket = DhcpSniffer.Receive(ref localEndoint);

我的两个程序都可以侦听网络中的 DHCP 消息,并且不会互相阻塞。 现在我想对 RTP 视频流流式传输到的端口 15120 做同样的事情。但是,这不起作用。我正在使用相同的代码,但没有成功,一次只有一个应用程序可以接收流,另一个将 运行 超时。

            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, port);
            //Create a new UDP Client and bind it to port 15120
            udpReceiver = new UdpClient();
            udpReceiver.ExclusiveAddressUse = false;    //this is an attempt to receive the stream on mutlible instances...this works for DHCP but not for RTP for some reason....
            udpReceiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // Connect even if socket/port is in use
            udpReceiver.Client.ReceiveTimeout = timeout;    //set the sockete timeout
            udpReceiver.Client.Bind(RemoteIpEndPoint);      //bind to the port from any IP
            //receive packets on port 15120
            Byte[] receiveBytes = udpReceiver.Receive(ref RemoteIpEndPoint);

希望有人能解答我的困惑

更新: 我发现它适用于 DHCP,因为它被发送到广播 IP (255.255.255.255)。现在我需要了解如何更改套接字行为以将我的 RTP 流视为已广播,以便我可以同时在两个应用程序中看到它。 (是的,我可以配置我的流源进行广播,但这不是目的)。 目标是重新配置 Socket 以按照解释的方式运行。不要将流保存在硬盘上或使用本地主机重定向它。

首先,不可能让多个程序监听同一个端口(据我所知这是一个很大的安全冲突)

你可以做的是使用一个网络管理器来监听你的端口(我们称之为端口 8080),然后它将信息重定向到你的应用程序端口(App1 可以使用端口 8081,App2 可以使用端口 8082)。要么你自己写,使用 Flask 监听 8080,然后将包重新路由到 localhost:8081 和 localhost:8082 可能是一个简单快速的解决方案。

这样做可以帮助您保护网络,并且您可以根据需要重定向到任意数量的端口,就像 docker 集群将传入网络平衡到其集群一样。

无法使用多个程序访问单播 UDP 包中的数据,它仅适用于多播,没有通过配置 UdpClient

解决此问题的“简单”方法