Java Reference
In-Depth Information
is the address of the machine that sent it (the source address). On the other hand, if the
datagram was created locally to be sent to a remote machine, this method returns the
address of the host to which the datagram is addressed (the destination address). This
method is most commonly used to determine the address of the host that sent a UDP
datagram, so that the recipient can reply.
public int getPort()
The
getPort()
method returns an integer specifying the remote port. If this datagram
was received from the Internet, this is the port on the host that sent the packet. If the
datagram was created locally to be sent to a remote host, this is the port to which the
packet is addressed on the remote machine.
public SocketAddress getSocketAddress()
The
getSocketAddress()
method returns a
SocketAddress
object containing the IP
address and port of the remote host. As is the case for
getInetAddress()
, if the datagram
was received from the Internet, the address returned is the address of the machine that
sent it (the source address). On the other hand, if the datagram was created locally to
be sent to a remote machine, this method returns the address of the host to which the
datagram is addressed (the destination address). You typically invoke this method to
determine the address and port of the host that sent a UDP datagram before you reply.
The net effect is not noticeably different than calling
getAddress()
and
getPort()
.
Also, if you're using nonblocking I/O, the
DatagramChannel
class accepts a
SocketAd
dress
but not an
InetAddress
and port.
public byte[] getData()
The
getData()
method returns a
byte
array containing the data from the datagram. It's
often necessary to convert the bytes into some other form of data before they'll be useful
to your program. One way to do this is to change the
byte
array into a
String
. For
example, given a
DatagramPacket
dp
received from the network, you can convert it to
a UTF-8
String
like this:
String
s
=
new
String
(
dp
.
getData
(),
"UTF-8"
);
If the datagram does not contain text, converting it to Java data is more difficult. One
approach is to convert the
byte
array returned by
getData()
into a
ByteArrayInput
Stream
. For example:
InputStream
in
=
new
ByteArrayInputStream
(
packet
.
getData
(),
packet
.
getOffset
(),
packet
.
getLength
());
You
must
specify the
offset
and the
length
when constructing the
ByteArrayInput
Stream
. Do not use the
ByteArrayInputStream()
constructor that takes only an array
as an argument. The array returned by
packet.getData()
probably has extra space in
it that was not filled with data from the network. This space will contain whatever