When does a DatagramPacket have its IP field changed from destinationIP to sourceIP?

时间:2019-05-19 04:12:10

标签: java datagram

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?

1 个答案:

答案 0 :(得分:1)

  

我认为对象本身不是通过网络发送的,但是其信息是通过网络发送的。

很明显!

Java对象仅存在于正在运行的Java程序的上下文中。在JVM之外,它根本不存在。

因此,即使在不同的Java应用程序之间发送序列化的对象时,您也不会真正发送对象。 (实际上,您正在发送对象状态的表示形式,可以反序列化该对象状态以给出一个 like 对象。)


回到您的问题。当您发送数据报包时,您不是在发送DatagramPacket对象。 DatagramPacket对象实际上是缓冲区,用于保存您正在发送的数据包或刚刚收到的数据包。

在您的情况下,您在具有(大概)不同IP地址的不同机器上的不同JVM中有两个不同的DatagramPacket对象。实际发生的是:

  • DatagramSocket::receiveDatagramPacket的远程地址设置为在接收到数据包时接收到的数据包的源IP。参见javadoc
  • DatagramSocket::send未设置DatagramPacket的远程地址。相反,它使用它作为数据报的目的地。参见javadoc