0

I need to send UDP Broadcast in the network. But I am getting confused. What I know is broadcast is not address specific and Multicast is group (Address) specific.

So, I am using DatagramSocket for sending and receiving DatagramPackets from the network.

What code I am writing is:

public class ComputerSender implements Runnable
{
    MulticastSocket socket;
    DatagramPacket packet;
    String command;
    public ComputerSender(String MAC)
    {
        try
        {
            socket = new MulticastSocket();
            JSONManager json = new JSONManager(MAC, WifiConstants.COMPUTER_NET_SCAN);
            json.setRecvMAC(WifiConstants.COMPUTER_NETWORK_ADDR);
            InetAddress addr = InetAddress.getByName(WifiConstants.COMPUTER_NETWORK_ADDR);
            command="Hello";
        }
        catch(Exception e)
        {
            Log.v("Exception:","Computer Constructor Error: "+e.toString());
        }
    }
    @Override
    public void run()
    {
        try
        {
            System.out.println(command);
            packet=new DatagramPacket(command.getBytes(),command.getBytes().length,InetAddress.getByName(WifiConstants.COMPUTER_NETWORK_ADDR), WifiConstants.COMPUTER_SEND_PORT);
            socket.setTimeToLive(100);
            socket.send(packet);
            System.out.println("Packet Sent");
            Thread.sleep(200);
        }
        catch(Exception e)
        {
            Log.v("Packet Sending Error: ","Computer Error: "+e.getMessage());
        }
        finally
        {
            socket.close();
        }
    }
}

I am not able to predict the above code is for Broadcast or Multicast. If Broadcast then what changes I need to make it for Multicast. and if Multicast then what changes I need to bring for Boradcast.

4

1 回答 1

2

这取决于 的值WifiConstants.COMPUTER_NETWORK_ADDR

对于广播,它需要是您网段的广播地址。例如,如果您的 IP 地址是 10.1.2.3,子网掩码为 255.255.0.0,那么 10.1.255.255 就是广播地址。

但是,多播地址使用多播地址范围内的组地址。

根据 IANA(http://www.iana.org/assignments/multicast-addresses/multicast-addresses.xml):

多播地址在 224.0.0.0 到 239.255.255.255 范围内。

因此,如果目标 IP 地址在该范围内,例如 224.224.1.2,那么任何侦听该多播组地址的客户端都会收到您的数据包。

于 2013-05-12T20:55:41.297 回答