-2

I am developing a chat application using UDP. I have a problem when getting the port number of another peer. I can get the peer's host address but not the port the response / request came from. Is is possible to get the port number of the peer who sent me the request / response.

Here is my code :

private Thread bcastListen = new Thread(PeerDiscovery.class.getSimpleName()
        + " broadcast listen thread") {
    @Override
    public void run() {
        try {

            byte[] buffy = new byte[5];
            buffy[2] = (byte) 4000;
            DatagramPacket rx = new DatagramPacket(buffy, buffy.length);

            while (!shouldStop) {
                try {
                    buffy[0] = 0;

                    bcastSocket.receive(rx);

                    int recData = decode(buffy, 1);
                    if (buffy[0] == QUERY_PACKET && recData == group) {
                        byte[] data = new byte[5];
                        data[0] = RESPONSE_PACKET;
                        encode(peerData, data, 1);
                        DatagramPacket tx
                                = new DatagramPacket(data, data.length, rx.getAddress(), port);
                        System.out.println(peerData);
                        lastResponseDestination = rx.getAddress();
                        bcastSocket.send(tx);
                    } else if (buffy[0] == RESPONSE_PACKET) {
                        if (responseList != null && !rx.getAddress().equals(lastResponseDestination)) {
                            synchronized (responseList) {
                                responseList.add(new Peer(rx.getAddress(), rx.getPort())); //here am trying to get  the port of the host which the response came from (Doesn't work)
                            }
                        }
                    }
                } catch (SocketException se) {
                    System.out.println("Some exception");
                }
            }

            bcastSocket.disconnect();
            bcastSocket.close();
        }

Thank you for your time.

Troller
  • 1,108
  • 8
  • 29
  • 47

1 Answers1

1

The source address of an incoming datagram is available via DatagramPacket.getPort().

but not the port

I don't know why not. Did you consider consulting the Javadoc?

NB the easy way to do what you're doing is to just send the received packet. No need to construct another one.

bcastSocket.disconnect();

You haven't called bcastSocket.connect(), so this line of code is futile. Remove it.

user207421
  • 305,947
  • 44
  • 307
  • 483