I am trying to get familiar with the Datagram system in java for a project, currently, we are only working with UDP packages.
To send a message we set the destination ip on the DatagramPacket.
/*
* The fields of this class are package-private since
* DatagramSocketImpl classes needs to access them.
*/
byte[] buf;
int offset;
int length;
int bufLength;
InetAddress address;
int port;
Doing this, the "address" field becomes the destination address, yet when we receive the package, that field corresponds to the source's.
I think that the object itself is not sent on over the network, but its information is.
I have briefly checked the source code of both DatagramPacket and DatagramSocket, but did not seem to find any instance where that "address" field was changed.
My guess is that the DatagramPacket class only stores one IP because the other one is the machine's, and when the message is sent over the network, the UDP contains both IPs, which then is processed by the DatagramSocket.receive() and places the missing (source) address on the Datagram. Is that correct?
I think that the object itself is not sent on over the network, but its information is.
Obviously!
A Java object only exists in the context of a running Java program. Outside of the JVM it simply doesn't exist.
So even when send a serialized object between different Java applications, you are not really sending the object. (You are actually sending a representation of the object's state that can be deserialized to give a similar object.)
Back to your question. When you send a datagram packet you are not sending a DatagramPacket
object. The DatagramPacket
objects are actually buffers that hold either a packet that you are sending, or a packet that you have just received.
In your case, you have two distinct DatagramPacket
objects in different JVMs on different machines with (presumably) different IP addresses. What actually happens is that: