user2698226
user2698226

Reputation: 1

Asynchronous UDP how to get ip and port from client in java?

This is my code:

channel = DatagramChannel.open();
        socket = channel.socket();
        channel.configureBlocking(false);
        socket.bind(new InetSocketAddress(3000));
        selector = Selector.open();
        channel.register(selector, SelectionKey.OP_READ);
        ByteBuffer buffer = ByteBuffer.allocate(65536);

        while(true)
        {
            if(selector.select()>0)
            {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator iterator = selectionKeys.iterator();
                while(iterator.hasNext())
                {
                    SelectionKey key = (SelectionKey)iterator.next();
                    iterator.remove();
                    InetSocketAddress isa = (InetSocketAddress) channel.getRemoteAddress();
                    if(key.isReadable())
                    {
                        System.out.print(isa.getAddress().getHostAddress()+":"+isa.getPort());
                    }
                }
            }
        }

the isa is null.I want to get the DatagramPack SocketAddress like socket.receive(DatagramPack); but i dont know channel how to get it. Use Channel.getSocketAddress() retun Null.

Upvotes: 0

Views: 1158

Answers (1)

Flavio
Flavio

Reputation: 11977

UDP is a connectionless protocol, so you will not be able to find the remote address of the channel, since there is no such thing. Once you open a UDP port for listening, everybody can send you messages, without establishing a direct connection. Every message you receive can potentially come from a different sender.

What you can do is to retrieve the remote address of the message. Check the DatagramChannel.receive() method: it will fill the buffer with the message, and return the address of the sender of that particular message.

Upvotes: 2

Related Questions