Java Reference
In-Depth Information
// use the socket...
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
finally
{
try
{
if
(
server
!=
null
)
server
.
close
();
}
catch
(
IOException
ex
)
{
}
}
In Java 7,
DatagramSocket
implements
AutoCloseable
so you can use try-with-
resources:
try
(
DatagramSocket
server
=
new
DatagramSocket
())
{
// use the socket...
}
It's never a bad idea to close a
DatagramSocket
when you're through with it; it's partic‐
ularly important to close an unneeded socket if the program will continue to run for a
significant amount of time. For example, the
close()
method was essential in
Example 12-4
,
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 upon
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. 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. Use this method if you created a
DatagramSock
et
with an anonymous port and want to find out what port the socket has been as‐
signed. For example:
DatagramSocket
ds
=
new
DatagramSocket
();
System
.
out
.
println
(
"The socket is using port "
+
ds
.
getLocalPort
());
public InetAddress getLocalAddress()
A
DatagramSocket
's
getLocalAddress()
method returns an
InetAddress
object that
represents the local address to which the socket is bound. It's rarely needed in practice.
Normally, you either already know or simply don't care which address a socket is lis‐
tening to.
public SocketAddress getLocalSocketAddress()
The
getLocalSocketAddress()
method returns a
SocketAddress
object that wraps the
local interface and port to which the socket is bound. Like
getLocalAddress()
, it's a