2016-03-04 65 views
0

試圖從本地網絡中的設備接收UPnP廣播。我確實發現了很多類似的問題,並嘗試了一些建議,但都沒有成功的主題。我確實看到了Wireshark的UDP數據包,所以它們實際上是在我的電腦上收到的。有什麼建議麼?使用UdpClient收聽UPnP廣播

using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 

public class UDPListener 
{ 
    private const int listenPort = 1900; 

    private static void StartListener() 
    { 
     bool done = false; 

     IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, listenPort); 

     UdpClient listener = new UdpClient(); 
     listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);   
     listener.Client.Bind(localEndPoint); 
     listener.JoinMulticastGroup(IPAddress.Parse("239.255.255.250")); 
     listener.MulticastLoopback = true; 

     IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0); 

     try 
     { 
      while (!done) 
      { 
       Console.WriteLine("Waiting for broadcast"); 
       var bytes = listener.Receive(ref groupEP); 

       Console.WriteLine("Received broadcast from {0} :\n {1}\n", 
        groupEP.ToString(), 
        Encoding.ASCII.GetString(bytes, 0, bytes.Length)); 

      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 
     finally 
     { 
      listener.Close(); 
     } 
    } 

    public static int Main() 
    { 
     StartListener(); 

     return 0; 
    } 
} 
+0

看看這個,也許它會幫助你:http://stackoverflow.com/questions/12794761/upnp-multicast-missing-答案 - 從-M-搜索發現 – Gusman

回答

1

感謝嘗試和錯誤我確實通過在綁定到多播組時指定我的本地地址來工作。我在示例中對地址進行了硬編碼,因爲它只是一個沙盒應用程序。使用IPAddress.Any不起作用。我不知道爲什麼。對於未來的參考和其他可憐的靈魂誰可能會尋找類似的東西:

using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 

public class UDPListener 
{ 
    private static void StartListener() 
    { 
     bool done = false; 

     IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 1900); 

     UdpClient listener = new UdpClient(); 
     listener.Client.Bind(localEndPoint); 
     listener.JoinMulticastGroup(IPAddress.Parse("239.255.255.250"), IPAddress.Parse("10.32.4.129")); 

     IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0); 

     try 
     { 
      while (!done) 
      { 
       Console.WriteLine("Waiting for broadcast"); 
       var bytes = listener.Receive(ref groupEP); 

       Console.WriteLine("Received broadcast from {0} :\n {1}\n", 
        groupEP.ToString(), 
        Encoding.ASCII.GetString(bytes, 0, bytes.Length)); 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 
     finally 
     { 
      listener.Close(); 
     } 
    } 

    public static int Main() 
    { 
     StartListener(); 

     return 0; 
    } 
}