C# SocketException with Multicast on XP

Deadly 提交于 2019-12-22 05:53:26

问题


The following C# code works correctly on Vista, but fails on XP with:

SocketException: An invalid argument was supplied.

The ErrorCode is 10022.

The firewall on XP has been 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?


回答1:


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

Edit: Just verified this in the MSDN docs (though it says only up to NT4):

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



来源:https://stackoverflow.com/questions/436659/c-sharp-socketexception-with-multicast-on-xp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!