我正在尝试从网络中的UPnP设备接收UPnP NOTIFY消息。但是当我发送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;
}
我找到了以下答案,但对我来说无法更改端口。有替代解决方案吗?
答案 0 :(得分:0)
这对你来说是一个纯粹的运气 - 相反,它的工作原因与预期不同。
您收到了NOTIFY消息,因为您开始收听多播作为该组的成员 - UPnP定期在1900年将其存在多播到邻居,没有搜索请求。
另一方面,当您发送M-SEARCH(多播,大概是)时,您应该留在并暂时监听短暂的端口,因为单播响应将会到达那里。