首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >多播UDP:通常只允许每个套接字地址(协议/网络地址/端口)使用一次

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

Stack Overflow用户
提问于 2018-06-05 04:34:43
回答 1查看 654关注 0票数 1

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

当我运行发送器程序(它也监听该端口)时,我在UdpClient listener = ...行得到以下错误:

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();
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-06-05 05:39:56

尝试一下,在绑定套接字之前,需要将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/

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50688372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档