Java Reference
In-Depth Information
public
void
bind
(
SocketAddress
endpoint
)
throws
IOException
public
void
bind
(
SocketAddress
endpoint
,
int
queueLength
)
throws
IOException
The primary use for this feature is to allow programs to set server socket options before
binding to a port. Some options are fixed after the server socket has been bound. The
general pattern looks like this:
ServerSocket
ss
=
new
ServerSocket
();
// set socket options...
SocketAddress
http
=
new
InetSocketAddress
(
80
);
ss
.
bind
(
http
);
You can also pass null for the
SocketAddress
to select an arbitrary port. This is like
passing 0 for the port number in the other constructors.
Getting Information About a Server Socket
The
ServerSocket
class provides two getter methods that tell you the local address and
port occupied by the server socket. These are useful if you've opened a server socket on
an anonymous port and/or an unspecified network interface. This would be the case,
for one example, in the data connection of an FTP session:
public
InetAddress
getInetAddress
()
This method returns the address being used by the server (the local host). If the local
host has a single IP address (as most do), this is the address returned by
InetAd
dress.getLocalHost()
. If the local host has more than one IP address, the specific
address returned is one of the host's IP addresses. You can't predict which address you
will get. For example:
ServerSocket
httpd
=
new
ServerSocket
(
80
);
InetAddress
ia
=
httpd
.
getInetAddress
();
If the
ServerSocket
has not yet bound to a network interface, this method returns null:
public
int
getLocalPort
()
The
ServerSocket
constructors allow you to listen on an unspecified port by passing
0 for the port number. This method lets you find out what port you're listening on. You
might use this in a peer-to-peer multisocket program where you already have a means
to inform other peers of your location. Or a server might spawn several smaller servers
to perform particular operations. The well-known server could inform clients on what
ports they can find the smaller servers. Of course, you can also use
getLocalPort()
to
find a nonanonymous port, but why would you need to?
Example 9-9
demonstrates.
Example 9-9. A random port
import
java.io.*
;
import
java.net.*
;