Java Reference
In-Depth Information
System.out.println(
"Client's IP Address is "
+
inetAddress.getHostAddress());
You can also create an instance of
InetAddress
from a host name or IP address using the
static
getByName
method. For example, the following statement creates an
InetAddress
for the host
liang.armstrong.edu
.
InetAddress address = InetAddress.getByName(
"liang.armstrong.edu"
);
Listing 31.3 gives a program that identifies the host name and IP address of the arguments
you pass in from the command line. Line 7 creates an
InetAddress
using the
getByName
method. Lines 8 and 9 use the
getHostName
and
getHostAddress
methods to get the
host's name and IP address. Figure 31.7 shows a sample run of the program.
F
IGURE
31.7
The program identifies host names and IP addresses.
L
ISTING
31.3
IdentifyHostNameIP.java
1
import
java.net.*;
2
3
public class
IdentifyHostNameIP {
4
public static void
main(String[] args) {
5
for
(
int
i =
0
; i < args.length; i++) {
6
try
{
7 InetAddress address = InetAddress.getByName(args[i]);
8 System.out.print(
"Host name: "
+ address.getHostName() +
" "
);
9 System.out.println(
"IP address: "
+ address.getHostAddress());
10 }
11
catch
(UnknownHostException ex) {
12 System.err.println(
"Unknown host or IP address "
+ args[i]);
13 }
14 }
15 }
16 }
get an
InetAddress
get host name
get host IP
31.6
How do you obtain an instance of
InetAddress
?
31.7
What methods can you use to get the IP address and hostname from an
InetAddress
?
✓
✓
Check
Point
A server can serve multiple clients. The connection to each client is handled by one
thread.
Key
Point
Multiple clients are quite often connected to a single server at the same time. Typically, a
server runs continuously on a server computer, and clients from all over the Internet can con-
nect to it. You can use threads to handle the server's multiple clients simultaneously—simply
Search WWH ::
Custom Search