Java Reference
In-Depth Information
public
class
RandomPort
{
public
static
void
main
(
String
[]
args
)
{
try
{
ServerSocket
server
=
new
ServerSocket
(
0
);
System
.
out
.
println
(
"This server runs on port "
+
server
.
getLocalPort
());
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
}
Here's the output of several runs:
$
java
RandomPort
This
server
runs
on
port
1154
D:
\
JAVA
\
JNP4
\
examples
\
9
>
java
RandomPort
This
server
runs
on
port
1155
D:
\
JAVA
\
JNP4
\
examples
\
9
>
java
RandomPort
This
server
runs
on
port
1156
At least on this system, the ports aren't truly random, but they are indeterminate until
runtime.
If the
ServerSocket
has not yet bound to a port,
getLocalPort()
returns -1.
As with most Java objects, you can also just print out a
ServerSocket
using its
to
String()
method. A
String
returned by a
ServerSocket
's
toString()
method looks
like this:
ServerSocket
[
addr
=
0.0
.
0.0
,
port
=
0
,
localport
=
5776
]
addr
is the address of the local network interface to which the server socket is bound.
This will be 0.0.0.0 if it's bound to all interfaces, as is commonly the case.
port
is always
0. The
localport
is the local port on which the server is listening for connections. This
method is sometimes useful for debugging, but not much more. Don't rely on it.
Socket Options
Socket options specify how the native sockets on which the
ServerSocket
class relies
send and receive data. For server sockets, Java supports three options:
• SO_TIMEOUT
• SO_REUSEADDR
• SO_RCVBUF
It also allows you to set performance preferences for the socket's packets.