2. NETWORKING CLASSES IN THE JDK
Through the classes in java.net, Java programs
can use TCP or UDP to communicate over the
Internet.
– The InetAddress, URL, URLConnection.
– Socket, and ServerSocket classes all use
TCP to communicate over the network.
– The DatagramPacket, DatagramSocket, and
MulticastSocket classes are for use with UDP
3. Accessing TCP/IP from Java is
straightforward.
The main functionality is in the following
classes:
– java.net.InetAddress : Represents an IP
address (either IPv4 or IPv6) and has
methods for performing DNS lookup (next
slide).
– java.net.Socket : Represents a TCP
socket.
– java.net.ServerSocket : Represents a
server socket which is capable of waiting for
4. INETADDRESS
• The InetAddress class is used to encapsulate both
the numerical IP address and the domain name for
that address.
• We interact with this class by using the name of an
IP host, which is more convenient and understandable
than its IP address.
• The InetAddress class hides the number inside.
Servers InteAddress have three main purposes:
ï‚— Encapsulates an address
ï‚— Performs name lookup (converting a host name into
an IP address)
ï‚— Performs reverse lookup (converting the address
into a host name)
6. Getter Methods
ï‚— public boolean isMulticastAddress()
ï‚— public String getHostName()
ï‚— public byte[] getAddress()
ï‚— public String getHostAddress()
7. Utility Methods
ï‚— public int hashCode()
ï‚— public boolean equals(Object o)
ï‚— public String toString()
8. Clases útiles en comunicaciones con
Sockets
Socket
ServerSocket
DatagramSocket
DatagramPacket
MulticastSocket
NetworkServer
NetworkClient
SocketImpl
9. Socket obtiene recursos IP
import java.net.*;
public class DireccionesIP{
String name;
public String Nombre(){
// Obtiene nombre LocalHost
try{
InetAddress address = InetAddress.getLocalHost();
name=address.getHostName();}
catch (UnknownHostException e){name="Imposible determinar Nombre del
Equipo";}
return name;
}
public String IP(){
// Obtiene Dirección IP LocalHost
try{
InetAddress address = InetAddress.getLocalHost();
name=address.getHostAddress();}
catch (UnknownHostException e){name="Imposible determinar Nombre del
Equipo";}
return name;
}