2013-03-10 41 views
1

我有一个应用程序运行在广播UDP数据包的iPhone上。我想编写一个控制台应用程序来读取我的PC上的UDP数据包。我试过了这个例子,是无法读取任何数据包:如何读取udp数据包发送到255.255.255.255

http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.aspx

我使用Wireshark的,并验证了UDP数据包被发送到255.255.255.255一个给定的端口上。如何读取C#应用程序中的数据包?

谢谢!

回答

0

这是一个简单的侦听器的C#代码,它应该没问题,但我在我的Mac上写了这个,所以我无法测试它。

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

public class UDPListener 
{ 
    public static int Main() 
    { 
     var done = false; 
     var listener = new UdpClient(31337); 
     var ipe = new IPEndPoint("255.255.255.255", 31337); 
     var data = String.Empty; 

     byte[] rec_array; 
     try 
     { 
      while (!done) 
      { 
       rec_array = listener.Receive(ref ipe); 
       Console.WriteLine("Received a broadcast from {0}", ipe.ToString()); 
       data = Encoding.ASCII.GetString(rec_array, 0, rec_array.Length); 
       Console.WriteLine("Received: {0}\r\rn", data); 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 

     listener.Close(); 
     return 0; 
    } 
} 
+0

显然,替换为您的实际端口31337。 – 2013-03-10 03:04:37

+0

这对我有效。我没有在端点中使用正确的IP地址。谢谢你的快速反应! – codemonkey 2013-03-10 05:40:14

+0

不客气,很高兴它的工作! – 2013-03-10 23:04:30