Java Reference
In-Depth Information
Example 8-6. Get a socket's information
import
java.net.*
;
import
java.io.*
;
public
class
SocketInfo
{
public
static
void
main
(
String
[]
args
)
{
for
(
String
host
:
args
)
{
try
{
Socket
theSocket
=
new
Socket
(
host
,
80
);
System
.
out
.
println
(
"Connected to "
+
theSocket
.
getInetAddress
()
+
" on port "
+
theSocket
.
getPort
()
+
" from port "
+
theSocket
.
getLocalPort
()
+
" of "
+
theSocket
.
getLocalAddress
());
}
catch
(
UnknownHostException
ex
)
{
System
.
err
.
println
(
"I can't find "
+
host
);
}
catch
(
SocketException
ex
)
{
System
.
err
.
println
(
"Could not connect to "
+
host
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
}
}
Here's the result of a sample run. I included
www.oreilly.com
on the command line twice
in order to demonstrate that each connection was assigned a different local port, re‐
gardless of the remote host; the local port assigned to any connection is unpredictable
and depends mostly on what other ports are in use. The connection to
login.ibi‐
blio.org
failed because that machine does not run any servers on port 80:
$
java SocketInfo www.oreilly.com www.oreilly.com www.elharo.com
login.ibiblio.org
Connected to www.oreilly.com/208.201.239.37 on port 80 from port 49156 of
/192.168.254.25
Connected to www.oreilly.com/208.201.239.37 on port 80 from port 49157 of
/192.168.254.25
Connected to www.elharo.com/216.254.106.198 on port 80 from port 49158 of
/192.168.254.25
Could not connect to login.ibiblio.org
Closed or Connected?
The
isClosed()
method returns true if the socket is closed, false if it isn't. If you're
uncertain about a socket's state, you can check it with this method rather than risking
an
IOException
. For example:
if
(
socket
.
isClosed
())
{
// do something...