简体   繁体   中英

Can DatagramSocket Receive multicast Packets

I have a code that runs in a thread, which i use to send a DatagramPacket to broadcast address of each NetworkInterface in the computer and also to a multicast group. It is as follows:

try {
    String decl="Mymessage";
    DatagramPacket ackdp;
    while(true)
        {
        Thread.sleep(3000);
        //First sending multicast (not broadcast) packet to a multicast group
        //231.26.179.75:37486
        ackdp=new DatagramPacket(s.getBytes(),s.length(),multicastGroup,port);
        BroadcastSocket.send(ackdp);
        //Now sending same message to broadcast address of each of the n/w interfaces
        Enumeration nwInterfaces = NetworkInterface.getNetworkInterfaces();
        while(nwInterfaces.hasMoreElements())
                {
                NetworkInterface ni=(NetworkInterface) nwInterfaces.nextElement();
                if(ni.isLoopback()||!ni.isUp())
                        continue;
                for(InterfaceAddress ifa:ni.getInterfaceAddresses())
                        {
                        InetAddress broadcastIP=ifa.getBroadcast();
                        if(broadcastIP==null)
                                continue;
                        ackdp=new DatagramPacket(s.getBytes(),s.length(),broadcastIP,port);
                        BroadcastSocket.send(ackdp);
                        //port is same here :37486 (ip varies with network interface)
                        }
                }
        }
    } catch (Exception ex) {ex.printStackTrace();}

My question is: Can i receive both (multicast and broadcast) packets using same DatagramSocket? Note that both are sent to same port. Should i open a MulticastSocket or a DatagramSocket at the port 37486 to receive both packets?

(Packets are send from PC but received on Android)

Can DatagramSocket receive multicast Packets

No, because it can't join the multicast group.

You didn't ask, but for completeness:

Can DatagramSocket send multicast Packets

Yes.

Can MulticastSocket receive datagram (non-multicast) packets

Yes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM