以下C#代码在Vista上正常运行,但在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)); } } }
有任何想法吗?
在设置SocketOptionName.AddMembership选项之前,需要将套接字绑定到接口.
编辑:刚刚在MSDN文档中验证了这一点(尽管它只说到NT4):
Windows 98,Windows NT 4.0平台注意:在使用AddMembership作为optionName参数之前,必须调用Bind方法.