无法检测到Java UDP广播数据包

时间:2013-06-12 23:08:10

标签: java udp broadcast

我是网络编程新手。我想编写一个演示程序来学习如何发送UDP广播数据包。这是我写的小演示:

public class DatagramClient
{
   private final static int PACKETSIZE = 100 ;

   public static void main( String args[] )
   {

      DatagramSocket socket = null ;

      try
      {
         // Convert the arguments first, to ensure that they are valid
         InetAddress host = InetAddress.getByName( "67.194.218.255" ) ;
         int port         = 34567;//Integer.parseInt( args[1] ) ;

         // Construct the socket
         socket = new DatagramSocket() ;

         // Construct the datagram packet
         byte [] data = "Hello Server".getBytes() ;
         DatagramPacket packet = new DatagramPacket( data, data.length, host, port ) ;

         // Send it
         socket.send( packet ) ;

         // Set a receive timeout, 2000 milliseconds
         socket.setSoTimeout( 2000 ) ;

         // Prepare the packet for receive
         packet.setData( new byte[PACKETSIZE] ) ;

         // Wait for a response from the server
         socket.receive( packet ) ;

         // Print the response
         System.out.println( new String(packet.getData()) ) ;

      }
      catch( Exception e )
      {
         System.out.println( e ) ;
      }
      finally
      {
         if( socket != null )
            socket.close() ;
      }
   }
}



public class DatagramServer
{

   private final static int PACKETSIZE = 100 ;

   public static void main( String args[] )
   {
      try
      {

         // Convert the argument to ensure that is it valid

         int port = 34567;

         // Construct the socket
         DatagramSocket socket = new DatagramSocket( port ) ;
         socket.setBroadcast(true);

         System.out.println( "The server is ready..." ) ;


         for( ;; )
         {
            // Create a packet
            DatagramPacket packet = new DatagramPacket( new byte[PACKETSIZE], PACKETSIZE ) ;

            // Receive a packet (blocking)
            socket.receive( packet ) ;

            // Print the packet
            System.out.println( packet.getAddress() + " " + packet.getPort() + ": " + new String(packet.getData()) ) ;

            // Return the packet to the sender
            socket.send( packet ) ;
        }  
     }
     catch( Exception e )
     {
        System.out.println( e ) ;
     }
  }
}

Wireshark没有检测到数据包,但我无法弄清楚哪里出错了。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

您的目的地地址67.194.218.25567.194.218/24网络的广播地址,但您的实际网络设置可能不同,因此您必须使用正确的广播地址。

最简单的解决方案是使用尽可能广泛的广播地址255.255.255.255

如果这不起作用,您可能希望将目标地址缩小到实际网络。使用您的IP地址和您的网络掩码应该允许您通过将IP地址与反向网络掩码进行或运算来计算广播地址:例如, IP=192.168.1.7; mask=255.255.255.0 - > broadcast = 192.168.1.7 || 0.0.0.255 = 192.168.1.255

为简单起见,您还可以使用ipcalc(网络计算器);甚至有online version