Mutlcast UDP:通常只允许使用每个套接字地址(协议/网络地址/端口)

时间:2018-06-04 20:34:43

标签: .net sockets udpclient

我正在尝试使用UDPClient来侦听多播IP(UDP端口3000)数据包。

当我确实运行发送程序时(也会侦听该端口)然后我在UdpClient监听器上得到以下错误= ...

System.Net.Sockets.SocketException: 
 'Only one usage of each socket address (protocol/network address/port) is normally permitted'

但是,如果它没有运行,我没有收到该错误,但程序会锁定等待数据包到达。

该计划的全文如下:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Vtunnel
{
    public class UDPListener
    {
        private const int listenPort = 3000;
        private const string multicastIP = "239.0.0.0";
        private const string myIP = "10.4.30.239";

        public static void StartListener() { 
            bool done = false;
            IPAddress listenAddress;
            IPAddress myAddress;

            IPAddress.TryParse(multicastIP, out listenAddress);
            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(listenAddress, listenPort);

            try
            {
                while (!done)
                {
                    Console.WriteLine("Waiting for multicast");
                    byte[] bytes = listener.Receive(ref groupEP);

                    Console.WriteLine("Received multicast from {0} :\n {1}\n",
                        groupEP.ToString(),
                        Encoding.ASCII.GetString(bytes, 0, bytes.Length));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                listener.Close();
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            UDPListener.StartListener();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

试试这个,你需要在绑定之前将SO_REUSEADDR标志设置为套接字。

Dim listener As New UdpClient()
listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, True)
listener.Client.Bind(New IPEndPoint(IPAddress.Any, listenPort))
listener.JoinMulticastGroup(listenAddress)

来源:

https://stackoverflow.com/a/577905/1486185

http://www.jarloo.com/c-udp-multicasting-tutorial/