我正在尝试从我的网络中的UPnP设备接收UPnP通知消息。但是当我发送M-SEARCH消息时,我有时得不到答案。我的代码看起来像这样:
public bool StartListener()
{
if (this.ssdpSocket == null)
{
IPAddress localIpAddress = IPAddress.Any;
IPEndPoint localIpEndpoint = new IPEndPoint(localIpAddress, SsdpPort);
try
{
this.ssdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.ssdpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
this.ssdpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 16384);
this.ssdpSocket.Bind(localIpEndpoint);
this.ssdpSocket.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse(SsdpMulticastAddress), localIpAddress));
this.ssdpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 2);
this.ssdpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, true);
this.culture = Thread.CurrentThread.CurrentUICulture;
this.workerThreadListener = new WorkerThread(this.ssdpSocket, this.HandleSsdpMessage);
this.workerThreadListener.Start();
Log.InfoFormat("SSDP server bind successful [{0}]", localIpEndpoint);
return true;
}
catch (Exception exception)
{
Log.Info(string.Format("SSDP server bind failed [{0}]", localIpEndpoint), exception);
throw;
}
}
return false;
}
我找到了以下答案,但对我来说,改变端口是不可能的。有没有别的解决办法?
"多播
这对你来说是一种纯粹的运气,而不是由于与预期不同的原因。
您收到通知消息,因为您开始以组成员的身份收听组播- UPnP定期在1900年向邻居多播它们的存在,没有搜索请求。
另一方面,当您发送M-SEARCH(可能是多播)时,您应该在临时端口上停留并侦听,因为单播响应将到达那里。