C # SocketException with multicast on XP

The following C # code works correctly in Vista, but with an XP error:

SocketException: An invalid argument was specified.

ErrorCode is 10022.

XP Firewall is disabled.

using System;
using System.Net;
using System.Net.Sockets;

public class SocketTest
{
    [STAThread]
    public static void Main()
    {
        MySocket s = new MySocket();

        Console.WriteLine("done");
        Console.ReadLine();
    }

    public class MySocket : Socket
    {
        public const ushort SocketTtl = 4;
        public const string Address = "239.255.255.250";

        public IPAddress IPAddress = IPAddress.Parse(Address);

        public MySocket()
            : base(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
        {
            SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
            SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, SocketTtl);

            // This line throws SocketException: An invalid argument was supplied
            // SocketException.ErrorCode: 10022
            SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress));
        }
    }
}

Any ideas?

+5
source share
1 answer

You need to bind the socket to the interface before setting the SocketOptionName.AddMembership parameter.

Edit: just check this in the MSDN docs (although it only speaks before NT4):

Windows 98, Windows NT 4.0 Platform Note. You must call the Bind method before using AddMembership as the optionName parameter.

+8
source

All Articles