P R
P R

Reputation: 1301

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!

Upvotes: 0

Views: 707

Answers (2)

Pastor Hampande
Pastor Hampande

Reputation: 1

Try getting hostAddress using InetAddress.getHostAddress, read the IP part and pass it to a variable.

InetAddress address = InetAddress.getByName("[variable]");

or

InetAddress address = InetAddress.getByAddress("[variable]");

I hope any of these would lead to a better way.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533920

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.

Upvotes: 1

Related Questions