Java Reference
In-Depth Information
All these constructors throw an
IOException
, specifically, a
BindException
, if the
socket cannot be created and bound to the requested port. An
IOException
when cre‐
ating a
ServerSocket
almost always means one of two things. Either another server
socket, possibly from a completely different program, is already using the requested
port, or you're trying to connect to a port from 1 to 1023 on Unix (including Linux and
Mac OS X) without root (superuser) privileges.
You can take advantage of this to write a variation on the
LowPortScanner
program of
the previous chapter. Rather than attempting to connect to a server running on a given
port, you instead attempt to open a server on that port. If it's occupied, the attempt will
fail.
Example 9-8
checks for ports on the local machine by attempting to create
Server
Socket
objects on them and seeing on which ports that fails. If you're using Unix and
are not running as root, this program works only for ports 1024 and above.
Example 9-8. Look for local ports
import
java.io.*
;
import
java.net.*
;
public
class
LocalPortScanner
{
public
static
void
main
(
String
[]
args
)
{
for
(
int
port
=
1
;
port
<=
65535
;
port
++)
{
try
{
// the next line will fail and drop into the catch block if
// there is already a server running on the port
ServerSocket
server
=
new
ServerSocket
(
port
);
}
catch
(
IOException
ex
)
{
System
.
out
.
println
(
"There is a server on port "
+
port
+
"."
);
}
}
}
}
Here's the output I got when running
LocalPortScanner
on my Windows workstation:
D:
\
JAVA
\
JNP4
\
examples
\
9
>
java
LocalPortScanner
There
is
a
server
on
port
135
.
There
is
a
server
on
port
1025
.
There
is
a
server
on
port
1026
.
There
is
a
server
on
port
1027
.
There
is
a
server
on
port
1028
.
Constructing Without Binding
The noargs constructor creates a
ServerSocket
object but does not actually bind it to
a port, so it cannot initially accept any connections. It can be bound later using the
bind()
methods: