java.net.DatagramPacket

The DatagramPacket class is a wrapper for an array of bytes from which data will be sent or into which data will be received. It also contains the address and port to which the packet will be sent.

 public DatagramPacket(byte[] data, int length)
 public DatagramPacket(byte[] data, int length, InetAddress host, int port)
You construct a DatagramPacket object by passing an array of bytes and the number of those bytes to send to the DatagramPacket() constructor like this:

  String s = "My first UDP Packet"
  byte[] b = s.getBytes();
  DatagramPacket dp = new DatagramPacket(b, b.length);
Normally you'll also pass in the host and port to which you want to send the packet:

try {
  InetAddress metalab = new InetAddess("metalab.unc.edu");
  int chargen = 19;
  String s = "My second UDP Packet"
  byte[] b = s.getBytes();
  DatagramPacket dp = new DatagramPacket(b, b.length, ia, chargen);
}
catch (UnknownHostException e) {
  System.err.println(e);
}
The byte array that's passed to the constructor is stored by reference, not by value. If you cahnge it's contents elsewhere, the contents of the DatagramPacket change as well.

DatagramPackets themselves are not immutable. You can change the data, the length of the data, the port, or the address at any time with these four methods:

 public synchronized void setAddress(InetAddress host)
 public synchronized void setPort(int port)
 public synchronized void setData(byte buffer[])
 public synchronized void setLength(int length)
You can retrieve these items with these four get methods:

 public synchronized InetAddress getAddress()
 public synchronized int getPort()
 public synchronized byte[] getData()
 public synchronized int getLength()
These methods are primarily useful when you're receiving datagrams.


Previous | Next | Top
Last Modified April 22, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu