Search code examples
javamulticastdatagram

Network Discovery via datagram sockets: Multicasting


I'm implementing the example where a server listens for any active clients in the network.

I'm using Datagram sockets for the server to do the multicast and clients to respon to the server.

public void run() {

    try {
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        DatagramSocket dSock = new DatagramSocket(4445);
        dSock.receive(packet);
        int byteCount = packet.getLength();
        ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf);
        ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(byteStream));
        }

}

and on the client's side:

public void run() {
    {
     ObjectOutputStream os = null;
        try {
            InetAddress address = InetAddress.getByName("Server's IP");//Note!
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream(15000);
            os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
            os.flush();
              os.flush();
            byte[] sendBuf = byteStream.toByteArray();
            DatagramPacket packet = new DatagramPacket(sendBuf, sendBuf.length, address, 4445);
            int byteCount = packet.getLength();
            }
     }

}

In the above Eg, the Client has to know the server's IP apriori(hardcode). How can I modify the code on the server's side so that the server sends it's IP to the client and client responds to it?

I was able to do this using sockets but is it possible using datagram sockets?

Thanks!


Solution

  • You could use DatgramPacket.getAddress() and reply to the sender

    Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.