Java Reference
In-Depth Information
chapter 2
Basic Sockets
Y ou are now ready to learn about writing your own socket applications. We begin by
demonstrating how Java applications identify network hosts. Then, we describe the creation
of TCP and UDP clients and servers. Java provides a clear distinction between using TCP and
UDP, defining a separate set of classes for both protocols, so we treat each separately.
2.1
Socket Addresses
IP uses 32-bit binary addresses to identify communicating hosts. A client must specify the
IP address of the host running the server program when it initiates communication; the
network infrastructure uses the 32-bit destination address to route the client's information
to the proper machine. Addresses can be specified in Java using a string that contains ei-
ther the dotted-quad representation of the numeric address (e.g., 169.1.1.1) or a name (e.g.,
server.example.com ). Java encapsulates the IP addresses abstraction in the InetAddress class
which provides three static methods for creating InetAddress instances. getByName() and
getAllByName() take a name or IP address and return the corresponding InetAddress instance(s).
For example, InetAddress . getByName("192.168.75.13") returns an instance identifying the IP
address 192.168.75.13. The third method, getLocalHost() , returns an InetAddress instance con-
taining the local host address. Our first program example, InetAddressExample.java , demon-
strates the use of InetAddress . The program takes a list of names or IP addresses as command-
line parameters and prints the name and an IP address of the local host, followed by names
and IP addresses of the hosts specified on the command line.
InetAddressExample.java
0 import java.net.*; // for InetAddress
1
2 public class InetAddressExample {
3
9
 
Search WWH ::




Custom Search