简体   繁体   中英

How to bind remote socket address in DatagramSocket

How to Set Remote Machine address in the UDP socket, That should be returned while the receiver getting the socket address?

My Code:

DatagramSocket socket = new DatagramSocket();

packet = new DatagramPacket(new byte[10],10);

packet.setAddress(InetAddress.getByName(hostName));

packet.setPort(portNum);

byte[] data = message.getBytes();

packet.setData(data);

packet.setLength(data.length);

socket.send(packet);
socket.close();

But this create a socket with my local address, receiver receives my address instead of that remote host address.

What is the solution for this?

You are the one making the request, so your address will be the one that gets submitted for the response. If you are wanting the remote machine to receive the response, the UDP connection (Datagram Socket Connection) must be established by the remote machine and not your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM