Вопрос

I've written a Java RDT client/server program that exchanges datagram packets to correct packet corruption and loss. The final bit of code I added requires that I compare each packet's source address to the address of the original packet.

   //global
    InetAddress originalSender;

    //C'tor
    originalSender = null;

        ...


//primary method
    public byte[] rdt_receive() throws IOException
        { 
            while (true) {

                DatagramPacket recPacket = new DatagramPacket(new byte [PACKET_SIZE], PACKET_SIZE);
                dgSock.receive(recPacket);

                if (originalSender == null) {
                    System.out.println("Address is set!\n");
                    originalSender = recPacket.getAddress();
                }

                if( originalSender != recPacket.getAddress() ) {

                    System.out.println("Wrong sender!");
                    sendAck((short) (expectedSequence == 0 ? 1 : 0), recPacket.getSocketAddress());
                    continue;
                } 
    // continue method...

"Address is set" is never printed so if(originalSender == null)never returns true, even for the first packet. I've also tried SocketAddress and .getSocketAddress() to no avail. Help is much appreciated.

EDIT: "Wrong sender" is printed in an infinite loop. I'm running both client and server on the same computer and the first received packet is successfully written to a file. The program works before adding the block of if statements, correctly sending a text file and closing both client and server.

Are InetAddress/SocketAddress automatically assigned by the OS if set to null?

Это было полезно?

Решение

You can't compare InetAddresses with ==. You need to call equals().

But you don't need this. Just connect() the socket to the original sender when you get the first packet. Then UDP will do the filtering for you.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top