0% found this document useful (0 votes)
63 views5 pages

Public Class Datagramsocket Extends Object

The DatagramSocket class in Java represents a socket for sending and receiving datagram packets using UDP. It has three constructors - one that assigns an anonymous port for clients, and two others that allow binding to a specific port, either for all network interfaces or a particular one. Datagrams can be sent by passing a DatagramPacket to the socket's send method, and received into a DatagramPacket using the receive method. When done, the socket should be closed to free the local port for other use.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views5 pages

Public Class Datagramsocket Extends Object

The DatagramSocket class in Java represents a socket for sending and receiving datagram packets using UDP. It has three constructors - one that assigns an anonymous port for clients, and two others that allow binding to a specific port, either for all network interfaces or a particular one. Datagrams can be sent by passing a DatagramPacket to the socket's send method, and received into a DatagramPacket using the receive method. When done, the socket should be closed to free the local port for other use.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 5

The DatagramSocket Class

To send or receive a DatagramPacket, you need to open a datagram socket. In Java, a


datagram socket is created and accessed through the DatagramSocket class:
public class DatagramSocket extends Object
All datagram sockets are bound to a local port, on which they listen for incoming data
and which they place in the header of outgoing datagrams. If you're writing a client, you
don't care what the local port is, so you call a constructor that lets the system assign an
unused port (an anonymous port). This port number is placed in any outgoing datagrams
and will be used by the server to address any response datagrams. If you're writing a
server, clients need to know on which port the server is listening for incoming datagrams;
therefore, when a server constructs a DatagramSocket, it must specify the local port on
which it will listen. However, the sockets used by clients and servers are otherwise
identical: they differ only in whether they use an anonymous (system-assigned) or a well-
known port. There's no distinction between client sockets and server sockets, as there is
with TCP; there is no such thing as a DatagramServerSocket.

The Constructors
The DatagramSocket class has three constructors that are used in different situations, much
like the DatagramPacket class. The first constructor opens a datagram socket on an
anonymous local port. The second constructor opens a datagram socket on a well-known
local port that listens to all local network interfaces. The third constructor opens a
datagram socket on a well-known local port on a specific network interface. All three
constructors deal only with the local address and port. The remote address and port are
stored in the DatagramPacket, not the DatagramSocket. Indeed, one DatagramSocket can send
and receive datagrams from multiple remote hosts and ports.
public DatagramSocket( ) throws SocketException
This constructor creates a socket that is bound to an anonymous port. For example:
try {
DatagramSocket client = new DatagramSocket( );
// send packets...
}
catch (SocketException e) {
System.err.println(e);
}
You would use this constructor in a client that initiates a conversation with a server. In
this scenario, you don't care what port you are using, because the server will send its
response to the port from which the datagram originated. Letting the system assign a port
means that you don't have to worry about finding an unused port. If for some reason you
need to know the local port, you can find out with the getLocalPort( ) method described
later in this chapter.
The same socket may be used to receive the datagrams that a server sends back to it. A
SocketException is thrown if the socket can't be created. It's unusual for this constructor to
throw an exception; it's hard to imagine situations in which the socket could not be
opened, since the system gets to choose the local port.
public DatagramSocket(int port) throws SocketException
This constructor creates a socket that listens for incoming datagrams on a specific port,
specified by the port argument. You would use this constructor to write a server that has
to listen on a well-known port; if servers listened on anonymous ports, clients would not
be able to contact them. A SocketException is thrown if the socket can't be created. There
are two common reasons for the constructor to fail: the specified port is already occupied,
or you are trying to connect to a port below 1,024 and you don't have sufficient privileges
(i.e., you are not root on a Unix system; for better or worse, other platforms allow anyone
to connect to low-numbered ports). TCP ports and UDP ports are not related. Two
unrelated servers or clients can use the same port number if one uses UDP and the other
uses TCP. Example 13.2 is a port scanner that looks for UDP ports in use on the local
host. It decides that the port is in use if the DatagramSocket constructor throws an
exception. As written, it looks at ports from 1,024 up to avoid Unix's requirement that it
run as root to bind to ports below 1,024. You can easily extend it to check ports below
1,024, however, if you have root access or are running it on Windows or a Mac.
The speed at which UDPPortScanner runs depends strongly on the speed of your
machine and its UDP implementation. I've clocked Example 13.2 at as little as two
minutes on a moderately powered SPARCstation and as long as an hour on a
PowerBook 5300. Here are the results from one SPARCstation: The high-numbered
UDP ports in the 30,000 range are Remote Procedure Call (RPC) services. Aside from
RPC, some common protocols that use UDP are NFS, TFTP, and FSP. It's much harder
to scan UDP ports on a remote system than to scan for remote TCP ports. Whereas there's
always some indication that your TCP packet has been received by a listening port
regardless of application layer protocol, UDP provides no such guarantees. To determine
that a UDP server is listening, you have to send it a packet it will recognize and respond
to.

public DatagramSocket(int port, InetAddress address) throws SocketException


This constructor is primarily used on multihomed hosts; it creates a socket that listens for
incoming datagrams on a specific port and network interface. The port argumentis the port
on which this socket listens for datagrams. As with TCP sockets, you need to be root on a
Unix system to create a DatagramSocket on a port below 1,024. The address argument is an
InetAddress object matching one of the host's network addresses. A SocketException is
thrown if the socket can't be created. There are three common reasons for this constructor
to fail: the specified port is already occupied, you are trying to connect to a port below
1,024 and you don't have sufficient privileges (i.e., you are not root on a Unix system), or
address is not the address of one of the system's network interfaces.

Sending and Receiving Datagrams


The primary task of the DatagramSocket class is to send and receive UDP datagrams. One
socket can both send and receive. Indeed, it can send and receive to and from multiple
hosts at the same time.

public void send(DatagramPacket dp) throws IOException


Once a DatagramPacket is created and a DatagramSocket is constructed, you send the packet
by passing it to the socket's send( ) method. For example, if theSocket is a DatagramSocket
object and theOutput is a DatagramPacket object, you send theOutput using theSocket like this:
theSocket.send(theOutput);
If there's a problem sending the data, an IOException may be thrown. However, this is less
common with DatagramSocket than Socket or ServerSocket, since the unreliable nature of UDP
means you won't get an exception just because the packet doesn't arrive at its destination.
You may get an IOException if you're trying to send a larger datagram than your host's
native networking software supports, but then again you may not. This depends heavily
on the native UDP software in the OS and the native code that interfaces between this and
Java's DatagramSocketImpl class. This method may also throw a SecurityException if the
SecurityManager won't let you communicate with the host to which the packet is addressed.
This is primarily a problem for applets.

public void receive(DatagramPacket dp) throws IOException


This method receives a single UDP datagram from the network and stores it in the pre-
existing DatagramPacket object dp. Like the accept( ) method in the ServerSocket class, this
method blocks the calling thread until a datagram arrives. If your program does anything
besides wait for datagrams, you should call receive( ) in a separate thread. The datagram's
buffer should be large enough to hold the data received. If not, receive( ) places as much
data in the buffer as it can hold; the rest is lost. It may be useful to remember that the
maximum size of the data portion of a UDP datagram is 65,507 bytes. (That's the 65,536-
byte maximum size of an IP datagram minus the 20- byte size of the IP header and the 8-
byte size of the UDP header.) Some application protocols that use UDP further restrict
the maximum number of bytes in a packet; for instance, NFS uses a maximum packet
size of 8,192 bytes. If there's a problem receiving the data, an IOException may be thrown.
In practice, this is rare. Unlike send( ), this method does not throw a SecurityException if an
applet receives a datagram from other than the applet host. However, it will silently
discard all such packets. (This behavior prevents a denial-of-service attack against
applets that receive UDP datagrams.)

public void close( )


Calling a DatagramSocket object's close( ) method frees the port occupied by that socket. For
example:
try {
DatagramSocket theServer = new DatagramSocket( );
theServer.close( );
}
catch (SocketException e) {
System.err.println(e);
}
It's never a bad idea to close a DatagramSocket when you're through with it; it's particularly
important to close an unneeded socket if your program will continue to run for a
significant amount of time. For example, the close( ) method was essential in Example
13.2, UDPPortScanner: if this program did not close the sockets it opened, it would tie up
every UDP port on the system for a significant amount of time. On the other hand, if the
program ends as soon as you're through with the DatagramSocket, you don't need to close
the socket explicitly; the socket is automatically closed on garbage collection. However,
Java won't run the garbage collector just because you've run out of ports or sockets,
unless by lucky happenstance you run out of memory at the same time. On the gripping
hand, closing unneeded sockets never hurts and is good programming practice.

public int getLocalPort( )


A DatagramSocket's getLocalPort( ) method returns an int that represents the local port on
which the socket is listening. You would use this method if you created a DatagramSocket
with an anonymous port and want to find out what port you have been assigned. For
example:
try {
DatagramSocket ds = new DatagramSocket( );
System.out.println("The socket is using port " +
ds.getLocalPort( ));
}
catch (SocketException e) {
}

Managing Connections
Unlike TCP sockets, datagram sockets aren't very picky about whom they'll talk to. In
fact, by default they'll talk to anyone. But this is often not what you want. For instance,
applets are only allowed to send datagrams to and receive datagrams from the applet host.
An NFS or FSP client should accept packets only from the server it's talking to. A
networked game should listen to datagrams only from the people playing the game. In
Java 1.1, programs must manually check the source addresses and ports of the hosts
sending them data to make sure they're who they should be. However, Java 1.2 adds four
methods that let you choose which host you can send datagrams to and receive datagrams
from, while rejecting all others' packets.

public void connect(InetAddress host, int port) // Java 1.2


The connect( ) method doesn't really establish a connection in the TCP sense. However, it
does specify that the DatagramSocket will send packets to and receive packets from only the
specified remote host on the specified remote port. Attempts to send packets to a different
host or port will throw an IllegalArgumentException. Packets received from a different host
or a different port will be discarded without an exception or other notification. A security
check is made when the connect( ) method is invoked. If the VM is allowed to send data to
that host and port, then the check passes silently. Otherwise, a SecurityException is thrown.
However, once the connection has been made, send( ) and receive( ) on that DatagramSocket
no longer make the security checks they'd normally make.

public void disconnect()


The disconnect( ) method breaks the "connection" of a connected DatagramSocket so that it
can once again send packets to and receive packets from any host and port.

public int getPort( )


If and only if a DatagramSocket is connected, the getPort( ) method returns the remote port to
which it is connected. Otherwise, it returns -1.

public InetAddress getInetAddress( )


If and only if a DatagramSocket is connected, the getInetAddress( ) method returns the address
of the remote host to which it is connected. Otherwise, it returns null.

You might also like