Dr.YSG
Dr.YSG

Reputation: 7591

Mutlcast UDP: Only one usage of each socket address (protocol/network address/port) is normally permitted

I am trying to use UDPClient to listen for multicast IP (UDP port 3000) packets.

When I do have the sender program running (which also listens to that port) then I get the following error on line UdpClient listener = ...

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

However, if it is not running, I don't get that error, but the program locks on waiting for the packets to arrive.

The full text of the program is:

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

Upvotes: 1

Views: 995

Answers (1)

PavlinII
PavlinII

Reputation: 1083

Try this, you'll need to set SO_REUSEADDR flag to the socket before it gets binded.

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

Sources:

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

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

Upvotes: 3

Related Questions