2009-01-12 15 views
5

以下C#代码在Vista上正常工作,但在XP上失败:C#SocketException与多播在XP上

SocketException:提供了无效参数。

ErrorCode是10022.

XP上的防火墙已被禁用。

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

任何想法?

回答

8

在设置SocketOptionName.AddMembership选项之前,您需要将套接字绑定到接口。

编辑:刚才在MSDN文档验证了这一点(虽然它说只到NT4):

的Windows 98,Windows NT 4.0的平台说明:使用AddMembership作为OPTIONNAME之前,必须调用bind方法参数。

+0

为什么这会导致XP问题,但不是在Vista上? – Jeffrey 2009-01-12 20:52:00