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)