0

我是网络编程的新手。我想编写一个演示程序来学习如何发送 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 没有检测到数据包,但我不知道哪里出了问题。提前致谢!

4

1 回答 1

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(网络计算器);甚至还有一个在线版本

于 2013-06-13T10:16:32.823 回答