Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views21 pages

AJP Unit-4

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

UNIT-4 Networking

3.1 Networking Basics

Computers running on the Internet communicate to each other using either the Transmission Control
Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:

When you write Java programs that communicate over the network, you are programming at the
application layer. Typically, you don't need to concern yourself with the TCP and UDP layers.
Instead, you can use the classes in the java.net package.

Java is a premier language for network programming. java.net package encapsulate large number of
classes and interface that provides an easy-to use means to access network resources. Here are some
important classes and interfaces of java.net package.
Classes:
CacheRequest InetAddress Proxy URL
CookieManager Socket Datagrampacket URLConnection
CookieHandler ServerSocket DatagramSocket
Interfaces:
CookiePolicy CookieStore SocketImplFactory
FileNameMap SocketOption ProtocolFamily

Through the classes in java.net, Java programs can use TCP or UDP to communicate over the
Internet. The 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.2 Network Layer Protocol:


Internet Protocol

The Internet Protocol (IP) is the method or protocol by which data is sent from one computer to
another on the Internet. Each computer (known as a host) on the Internet has at least one IP address
that uniquely identifies it from all other computers on the Internet.

1 Advanced java Programming


UNIT-4 Networking

Because a message is divided into a number of packets, each packet can, if necessary, be sent by a
different route across the Internet. Packets can arrive in a different order than the order they were
sent in. The Internet Protocol just delivers them. It's up to another protocol, the Transmission Control
Protocol (TCP) to put them back in the right order.

IP is a connectionless protocol, which means that there is no continuing connection between the end
points that are communicating. Each packet that travels through the Internet is treated as an
independent unit of data without any relation to any other unit of data. (The reason the packets do get
put in the right order is because of TCP, the connection-oriented protocol that keeps track of the
packet sequence in a message.)

Internet Protocol hierarchy contains several classes of IP Addresses to be used efficiently in various
situations as per the requirement of hosts per network. Broadly, the IPv4 Addressing system is
divided into five classes of IP Addresses. All the five classes are identified by the first octet of IP
Address.

Internet Corporation for Assigned Names and Numbers is responsible for assigning IP addresses.

The first octet referred here is the left most of all. The octets numbered as follows depicting dotted
decimal notation of IP Address:

The number of networks and the number of hosts per class can be derived by this formula:

When calculating hosts' IP addresses, 2 IP addresses are decreased because they cannot be assigned
to hosts, i.e. the first IP of a network is network number and the last IP is reserved for Broadcast IP.

Class A Address
The first bit of the first octet is always set to 0 (zero). Thus the first octet ranges from 1 – 127, i.e.

2 Advanced java Programming


UNIT-4 Networking

Class A addresses only include IP starting from 1.x.x.x to 126.x.x.x only. The IP range 127.x.x.x is
reserved for loopback IP addresses.

The default subnet mask for Class A IP address is 255.0.0.0

Class B Address
An IP address which belongs to class B has the first two bits in the first octet set to 10, i.e.

Class B IP Addresses range from 128.0.x.x to 191.255.x.x. The default subnet mask for Class B is
255.255.x.x.

Class C Address
The first octet of Class C IP address has its first 3 bits set to 110, that is:

Class C IP addresses range from 192.0.0.x to 223.255.255.x. The default subnet mask for Class C is
255.255.255.x.

Class D Address
Very first four bits of the first octet in Class D IP addresses are set to 1110, giving a range of:

Class D has IP address rage from 224.0.0.0 to 239.255.255.255. Class D is reserved for Multicasting.
In multicasting data is not destined for a particular host, that is why there is no need to extract host
address from the IP address, and Class D does not have any subnet mask.

Class E Address
This IP Class is reserved for experimental purposes only for R&D or Study. IP addresses in this class
ranges from 240.0.0.0 to 255.255.255.254. Like Class D, this class too is not equipped with any
subnet mask.

1st Octet Network/Host Hosts per


1st Octet Number
High ID Default Network
Class Decimal of
Order (N=Network, Subnet Mask (Usable
Range Networks
Bits H=Host) Addresses)
A 1 – 126* 0 N.H.H.H 255.0.0.0 126 (27 – 16,777,214

3 Advanced java Programming


UNIT-4 Networking

2) (224 – 2)
128 – 16,382 65,534 (216 –
B 10 N.N.H.H 255.255.0.0
191 (214 – 2) 2)
192 – 2,097,150
C 110 N.N.N.H 255.255.255.0 254 (28 – 2)
223 (221 – 2)
224 –
D 1110 Reserved for Multicasting
239
240 –
E 1111 Experimental; used for research
254

3.3 Transport layer protocols:

1. TCP

When two applications want to communicate to each other reliably, they establish a connection and
send data back and forth over that connection. This is analogous to making a telephone call. Like the
phone company, TCP guarantees that data sent from one end of the connection actually gets to the
other end and in the same order it was sent. Otherwise, an error is reported.

TCP provides a point-to-point channel for applications that require reliable communications. The
Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of
applications that require a reliable communication channel. The order in which the data is sent and
received over the network is critical to the success of these applications. When HTTP is used to read
from a URL, the data must be received in the order in which it was sent. Otherwise, you end up with a
jumbled HTML file, a corrupt zip file, or some other invalid information.

TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of
data between two computers.

2. UDP

The UDP protocol provides for communication that is not guaranteed between two applications on the
network. UDP is not connection-based like TCP. Rather, it sends independent packets of data,
called datagrams, from one application to another. Sending datagrams is much like sending a letter
through the postal service: The order of delivery is not important and is not guaranteed, and each
message is independent of any other. Sending datagrams is much like sending a letter through the mail
service: The order of delivery is not important and is not guaranteed, and each message is independent
of any others.

UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called
datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-
based like TCP.

Another example of a service that doesn't need the guarantee of a reliable channel is the ping
command. The purpose of the ping command is to test the communication between two programs

4 Advanced java Programming


UNIT-4 Networking

over the network. In fact, ping needs to know about dropped or out-of-order packets to determine how
good or bad the connection is. A reliable channel would invalidate this service altogether.

3.4 Application Layer Protocols


1. Domain Name System
The Domain Name System (DNS) works on Client Server model. It uses UDP protocol for transport
layer communication. DNS uses hierarchical domain based naming scheme. The DNS server is
configured with Fully Qualified Domain Names (FQDN) and email addresses mapped with their
respective Internet Protocol addresses.

A DNS server is requested with FQDN and it responds back with the IP address mapped with it.
DNS uses UDP port 53.

2. Simple Mail Transfer Protocol


The Simple Mail Transfer Protocol (SMTP) is used to transfer electronic mail from one user to
another. This task is done by means of email client software (User Agents) the user is using. User
Agents help the user to type and format the email and store it until internet is available. When an
email is submitted to send, the sending process is handled by Message Transfer Agent which is
normally comes inbuilt in email client software.

Message Transfer Agent uses SMTP to forward the email to another Message Transfer Agent
(Server side). While SMTP is used by end user to only send the emails, the Servers normally use
SMTP to send as well as receive emails. SMTP uses TCP port number 25 and 587.

Client software uses Internet Message Access Protocol (IMAP) or POP protocols to receive emails.

3. File Transfer Protocol


The File Transfer Protocol (FTP) is the most widely used protocol for file transfer over the network.
FTP uses TCP/IP for communication and it works on TCP port 21. FTP works on Client/Server
Model where a client requests file from Server and server sends requested resource back to the client.

FTP uses out-of-band controlling i.e. FTP uses TCP port 20 for exchanging controlling information
and the actual data is sent over TCP port 21.

The client requests the server for a file. When the server receives a request for a file, it opens a TCP
connection for the client and transfers the file. After the transfer is complete, the server closes the
connection. For a second file, client requests again and the server reopens a new TCP connection.

4. Post Office Protocol (POP)


The Post Office Protocol version 3 (POP 3) is a simple mail retrieval protocol used by User Agents
(client email software) to retrieve mails from mail server.

5 Advanced java Programming


UNIT-4 Networking

When a client needs to retrieve mails from server, it opens a connection with the server on TCP port
110. User can then access his mails and download them to the local computer. POP3 works in two
modes. The most common mode the delete mode, is to delete the emails from remote server after
they are downloaded to local machines. The second mode, the keep mode, does not delete the email
from mail server and gives the user an option to access mails later on mail server.

5. Hyper Text Transfer Protocol (HTTP)


The Hyper Text Transfer Protocol (HTTP) is the foundation of World Wide Web. Hypertext is well
organized documentation system which uses hyperlinks to link the pages in the text documents.
HTTP works on client server model. When a user wants to access any HTTP page on the internet,
the client machine at user end initiates a TCP connection to server on port 80. When the server
accepts the client request, the client is authorized to access web pages.

To access the web pages, a client normally uses web browsers, who are responsible for initiating,
maintaining, and closing TCP connections. HTTP is a stateless protocol, which means the Server
maintains no information about earlier requests by clients.

HTTP versions

 HTTP 1.0 uses non persistent HTTP. At most one object can be sent over a single TCP
connection.

 HTTP 1.1 uses persistent HTTP. In this version, multiple objects can be sent over a single
TCP connection.

3.5 Ports

Generally speaking, a computer has a single physical connection to the network. All data destined for
a particular computer arrives through that connection. However, the data may be intended for
different applications running on the computer. So how does the computer know to which application
to forward the data? Through the use of ports.

Data transmitted over the Internet is accompanied by addressing information that identifies the
computer and the port for which it is destined. The computer is identified by its 32-bit IP address,
which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit
number, which TCP and UDP use to deliver the data to the right application.

In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for
that port. A client can then rendezvous with the server at the server's port, as illustrated here:

6 Advanced java Programming


UNIT-4 Networking

The TCP and UDP protocols use ports to map incoming data to a particular process running on a
computer.

In datagram-based communication such as UDP, the datagram packet contains the port number of its
destination and UDP routes the packet to the appropriate application, as illustrated in this figure:

Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port
numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such
as HTTP and FTP and other system services. These ports are called well-known ports. Your
applications should not attempt to bind to them.

Port No. Description Port No. Description


1 TCP Port Service Multiplexer (TCPMUX) 118 SQL Services
5 Remote Job Entry (RJE) 119 Newsgroup (NNTP)
7 ECHO 137 NetBIOS Name Service
18 Message Send Protocol (MSP) 139 NetBIOS Datagram Service
20 FTP -- Data 143 Interim Mail Access Protocol (IMAP)
21 FTP -- Control 150 NetBIOS Session Service
22 SSH Remote Login Protocol 156 SQL Server
23 Telnet 161 SNMP
25 Simple Mail Transfer Protocol (SMTP) 179 Border Gateway Protocol (BGP)
Gateway Access Control Protocol
29 MSG ICP 190 (GACP)
37 Time 194 Internet Relay Chat (IRC)
42 Host Name Server (Nameserv) 197 Directory Location Service (DLS)
Lightweight Directory Access
43 WhoIs 389 Protocol (LDAP)
49 Login Host Protocol (Login) 396 Novell Netware over IP
53 Domain Name System (DNS) 443 HTTPS
Simple Network Paging Protocol
69 Trivial File Transfer Protocol (TFTP) 444 (SNPP)
70 Gopher Services 445 Microsoft-DS
79 Finger 458 Apple QuickTime
80 HTTP 546 DHCP Client
103 X.400 Standard 547 DHCP Server
108 SNA Gateway Access Server 563 SNEWS
109 POP2 569 MSN
110 POP3 1080 Socks
115 Simple File Transfer Protocol (SFTP)

7 Advanced java Programming


UNIT-4 Networking

3.6 InetAddress
InetAddress encapsulates both numerical IP address and the domain name for that address. Inet
address can handle both IPv4 and Ipv6 addresses. InetAddress class has no visible constructor. To
create an inet Address object, you have to use Factory methods.

Some commonly used InetAddress factory methods are.

Method Description

public static InetAddress getByName(String host) It returns the instance of InetAddress containing
throws UnknownHostException LocalHost IP and name.
public static InetAddress getLocalHost() It returns the instance of InetAdddress containing
throws UnknownHostException local host name and address.

public String getHostName() It returns the host name of the IP address.

public String getHostAddress() It returns the IP address in string format.

static InetAddress[] getAllByName (String Determines all the IP addresses of a host, given the
hostname) throws UnknownHostException host's name.

Some commonly used InetAddress instance methods are.

Method Description

public boolean equals(Object obj) compare this object with specified object

public byte[] getAddress() This method returns the IP address associated with this object as
an array of bytes in network order.

public String getHostAddress() This method returns a string representation of the IP address
associated with this object. For example: "206.175.64.78".
public String getHostName() Returns the hostname associated with this object.

public int hashCode() Returns the hashcode based on the IP address of the object.

public boolean isMulticastAddress() True if this object represents a multicast address; false otherwise.

toString This method returns a String that contains both the hostname and
IP address of this object.

Example:

import java.net.*;
class Test
{
public static void main(String[] args)
{

8 Advanced java Programming


UNIT-4 Networking

InetAddress address = InetAddress.getLocalHost();


System.out.println(address);
address = InetAddress.getByName("www.yahoo.com");
System.out.println(address);
InetAddress sw[] = InetAddress.getAllByName("www.google.com");
for(int i=0; i< sw.length; i++)
{
System.out.println(sw[i]);
}
}
}
Output:
Welcome-PC/59.161.87.227
www.yahoo.com/208.91.198.55
www.google.com/74.125.236.115
www.google.com/74.125.236.116
www.google.com/74.125.236.112
www.google.com/74.125.236.113
www.google.com/74.125.236.114
www.google.com/2404:6800:4009:802:0:0:0:1014

3.7 TCP/IP SOCKET PROGRAMMING

The two key classes from the java.net package used in creation of server and client programs are:

 ServerSocket
 Socket

A server program creates a specific type of socket that is used to listen for client requests (server
socket), In the case of a connection request, the program creates a new socket through which it will
exchange data with the client using input and output streams. The socket abstraction is very similar to
the file concept: developers have to open a socket, perform I/O, and close it. Figure 13.5 illustrates
key steps involved in creating socket-based server and client programs.

9 Advanced java Programming


UNIT-4 Networking

Socket class
In order to connect to a server over the internet (via TCP/IP) in Java, you need to create
a java.net.Socket and connect it to the server.

The Socket class has five constructors that a client uses to connect to a server:

SN Methods Description

1 public Socket(String host, int port) throws This method attempts to connect to the specified
UnknownHostException, IOException. server at the specified port. If this constructor does
not throw an exception, the connection is successful
and the client is connected to the server.

2 public Socket(InetAddress host, int port) This method is identical to the previous constructor,
throws IOException except that the host is denoted by an InetAddress
object.

3 public Socket(String host, int port, Connects to the specified host and port, creating a
InetAddress localAddress, int localPort) socket on the local host at the specified address and
throws IOException. port.

4 public Socket(InetAddress host, int port, This method is identical to the previous constructor,
InetAddress localAddress, int localPort) except that the host is denoted by an InetAddress
throws IOException. object instead of a String

5 public Socket() Creates an unconnected socket. Use the connect()


method to connect this socket to a server.

Here are some of the common methods of the Socket class:

SN Methods Description

1 public void connect(SocketAddress host, This method connects the socket to the specified
int timeout) throws IOException host. This method is needed only when you
instantiated the Socket using the no-argument
constructor.

2 public InetAddress getInetAddress() This method returns the address of the other
computer that this socket is connected to.

3 public int getPort() Returns the port the socket is bound to on the remote
machine.

4 public int getLocalPort() Returns the port the socket is bound to on the local
machine.

5 public SocketAddress Returns the address of the remote socket.


getRemoteSocketAddress()

6 public InputStream getInputStream() Returns the input stream of the socket. The input
throws IOException stream is connected to the output stream of the
remote socket.

10 Advanced java Programming


UNIT-4 Networking

7 public OutputStream getOutputStream() Returns the output stream of the socket. The output
throws IOException stream is connected to the input stream of the remote
socket

8 public void close() throws IOException Closes the socket, which makes this Socket object no
longer capable of connecting again to any server

ServerSocket Class

In order to implement a Java server that listens for incoming connections from clients via TCP/IP, you
need to use a java.net.ServerSocket .

The ServerSocket class has four constructors:

SN Methods Description

1 public ServerSocket(int port) throws Attempts to create a server socket bound to the
IOException specified port. An exception occurs if the port
is already bound by another application.

2 public ServerSocket(int port, int backlog) throws Similar to the previous constructor, the
IOException backlog parameter specifies how many
incoming clients to store in a wait queue.

3 public ServerSocket(int port, int backlog, Similar to the previous constructor, the
InetAddress address) throws IOException InetAddress parameter specifies the local IP
address to bind to. The InetAddress is used for
servers that may have multiple IP addresses,
allowing the server to specify which of its IP
addresses to accept client requests on

4 public ServerSocket() throws IOException Creates an unbound server socket. When using
this constructor, use the bind() method when
you are ready to bind the server socket

Here are some of the common methods of the ServerSocket class:

SN Methods Description

1 public int getLocalPort() Returns the port that the server socket is
listening on. This method is useful if you
passed in 0 as the port number in a constructor
and let the server find a port for you.

2 public Socket accept() throws IOException Waits for an incoming client. This method
blocks until either a client connects to the
server on the specified port or the socket times
out, assuming that the time-out value has been
set using the setSoTimeout() method.
Otherwise, this method blocks indefinitely

11 Advanced java Programming


UNIT-4 Networking

3 public void setSoTimeout(int timeout) Sets the time-out value for how long the server
socket waits for a client during the accept().

4 public void bind(SocketAddress host, int Binds the socket to the specified server and
backlog) port in the SocketAddress object. Use this
method if you instantiated the ServerSocket
using the no-argument constructor.

Example : Client server communication

import java.net.*;
import java.io.*;
public class SimpleServer
{
public static void main(String args[]) throws IOException
{
ServerSocket s = new ServerSocket(1254); // Register service on port 1254
Socket s1=s.accept(); // Wait and accept a connection

OutputStream out = s1.getOutputStream(); //geta stream


DataOutputStream dos = new DataOutputStream (out);
dos.writeUTF("Hi there"); // Send a string!

// Close the connection, but not the server socket


dos.close();
out.close();
s1.close();
}
}

import java.net.*;
import java.io.*;
public class SimpleClient
{
public static void main(String args[]) throws IOException
{
// Open your connection to a server, at port 1254
Socket s1 = new Socket("localhost",1254);

// Get an input file handle from the socket and read the input
InputStream In = s1.getInputStream();
DataInputStream dis = new DataInputStream(In);
String st = new String (dis.readUTF());
System.out.println(st);

dis.close();
In.close();
s1.close();

12 Advanced java Programming


UNIT-4 Networking

}
}

Output: hi there

3.8 UDP SOCKET PROGRAMMING


The previous example used the TCP sockets. As already said, TCP guarantees the delivery of packets
and preserves their order on destination. Sometimes these features are not required and since they
Socket Programming 353 do not come without performance costs, it would be better to use a lighter
transport protocol. This kind of service is accomplished by the UDP protocol which conveys datagram
packet s. Datagram packets are used to implement a connectionless packet delivery service supported
by the UDP protocol. Each message is transferred from source machine to destination based on
information contained within that packet. That means, each packet needs to have destination address
and each packet might be routed differently, and might arrive in any order. Packet delivery is not
guaranteed. The format of datagram packet is:

Msg | length | Host | serverPort

Java supports datagram communication through the following classes:

 DatagramPacket
 DatagramSocket: Datagram Socket is used to send or receive Datagrams .

Constructors of DatagramPacket

DatagramPacket ( byte[ ] buff , int len) Constructs a DatagramPacket for receiving


packets of length len.

DatagramPacket (byte[] buf, int off, int len) Constructs a DatagramPacket for receiving
packets of length len, specifying an offset of off
bytes into the buffer.

DatagramPacket ((byte[] buf, int len, Constructs a datagram packet for sending packets
InetAddress addr, int port) of length len to the specified port number on the
specified host.

DatagramPacker (byte[] buf, int off, int len, Constructs a datagram packet for sending packets
InetAddress addr, int port) of length len with offset off to the specified port
number on the specified host.

DatagramPacket (byte[] buf, int off, int len, Constructs a datagram packet for sending packets
SocketAddress addr) of length len with offset off to the specified port
number on the specified host.

Constructors of DatagramSocket

DatagramSocket () Constructs a datagram socket and binds it to any


available port on the local host.
DatagramSocket (DatagramSocketImpl impl) Creates an unbound datagram socket with the

13 Advanced java Programming


UNIT-4 Networking

specified DatagramSocketImpl.
DatagramSocket (int port) Constructs a datagram socket and binds it to the
specified port on the local host.
DatagramSocket (int port, InetAddress iaddr) Creates a datagram socket, bound to the specified
local address.
DatagramSocket (SocketAddress bindaddr) Creates a datagram socket, bound to the
specified local socket address.

Example:

public class UDPClient


{

public static void main(String args[])


{

DatagramSocket aSocket = null;

try
{
String s="hello, how are you";
aSocket = new DatagramSocket();
byte [] m = s.getBytes();
InetAddress aHost = InetAddress.getLocalHost();
int serverPort = 1234;
DatagramPacket request = new DatagramPacket(m, s.length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData()));
}
catch (Exception e) {
}

}
}

3.9 URL class


Java URL Class present in java.net package, deals with URL (Uniform Resource Locator) which
uniquely identify or locate resources on internet.

14 Advanced java Programming


UNIT-4 Networking

Constructor Desciption
URL (String spec) Creates a URL object from the String
representation.
URL (String protocol, String host, int port, String Creates a URL object from the specified protocol,
file) host, port number, and file.

URL (String protocol, String host, int port, String Creates a URL object from the specified protocol,
file, URLStreamHandler handler) host, port number, file, and handler.

URL (String protocol, String host, String file) Creates a URL from the specified protocol name,
host name, and file name.
URL (URL context, String spec) Creates a URL by parsing the given spec within a
specified context.
URL (URL context, String spec, Creates a URL by parsing the given spec with the
URLStreamHandler handler) specified handler within a specified context.

Methods of URL class


The URL class provides methods for retrieving individual components of the represented
URL (such as the protocol and the host name). It also provides comparison methods for determining if
two URL objects reference the same content.

Methods Description
protected void set(String protocol, String host, int Sets the fields of the URL. This is not a public
port, String file, String ref) method so that only URLStreamHandlers can
modify URL fields. URLs are otherwise constant.
public int getPort() Gets the port number. Returns -1 if the port is not
set.
public String getProtocol() Gets the protocol name.
public String getHost() Gets the host name.
public String getFile() Gets the file name.
public String getPath () Gets the path part of URL
public String getQuery () Gets the query part of URL

public boolean equals(Object obj) Compares two URLs. Returns true if and only if
they are equal, false otherwise.
public URLConnection openConnection() Creates (if not already in existance) a
throws IOException URLConnection object that contains a connection
to the remote object referred to by the URL.
public final InputStream openStream() throws Opens an input stream.
IOException
public final Object getContent() throws Gets the contents from this opened connection.
IOException

Example:

import java.net.*;
class Test
{
public static void main(String[] arg)
{
try
15 Advanced java Programming
UNIT-4 Networking

{
URL hp = new URL("http://www.yahoo.com:80/index");
System.out.println(hp.getProtocol());
System.out.println(hp.getPath());
System.out.println(hp.getHost());
System.out.println(hp.getFile());
System.out.println(hp.getPort());
}
catch(MalformedURLException e){}
}
}
Ouput:
http
/index
www.yahoo.com
/index
80

3.10 URLConnection class


The abstract class URLConnection is the superclass of all classes that represent a communications
link between the application and a URL. Instances of this class can be used both to read from and to
write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep
process:

1. The connection object is created by invoking the openConnection method on a URL.

2. The setup parameters and general request properties are manipulated.

3. The actual connection to the remote object is made, using the connect method.

4. The remote object becomes available. The header fields and the contents of the remote
object can be accessed.

Fields of URLConnection class

protected boolean allowUserInteraction If true allow user interactions in the URL being
examined
protected boolean connected If true, the communications link has been
established.
protected boolean doInput Setting the doInput flag to true allows the
application to read data from the URL connection.
protected boolean doOutput Setting the doOutput flag to true allows the
application to write data to the URL connection.
protected long ifModifiedSince Returns the time in milliseconds since last
modified.
protected URL url The URL represents the remote object on the
World Wide Web to which this connection is

16 Advanced java Programming


UNIT-4 Networking

opened.
protected boolean useCaches If true, the protocol is allowed to use caching
whenever it can.

Constructor of URLConnection class:

protected URLConnection(URL url) Constructs a URL connection to the specified


URL. A connection to the object referenced by the
URL is not created.

Methods of URLConnection class:

public abstract void connect()throws Opens a communications link to the resource


IOException referenced by this URL.
public URL getURL() Returns the value of this URLConnection's URL
field.
public int getContentLength() Returns the value of the content-length header
field.
public String getContentType() Returns the value of the content-type header
field.
public long getDate() Returns the value of the date header field.

public long getLastModified() Returns the value of the last-modified header


field. The result is the number of milliseconds
since January 1, 1970 GMT.
public Object getContent()throws IOException Retrieves the contents of this URL connection.

public Object getContent(Class[] classes)throws Retrieves the contents of this URL connection.
IOException

public Permission getPermission()throws Returns a permission object representing the


IOException permission necessary to make the connection
represented by this object.
public InputStream getInputStream()throws Returns an input stream that reads from this open
IOException connection.
public OutputStream getOutputStream()throws Returns an output stream that writes to this
IOException connection.

Example:

import java.net.*;
import java.io.*;

public class Demo


{
public static void main(String[] arg)
{
try
{

17 Advanced java Programming


UNIT-4 Networking

URL url=new URL("http://www.google.com");


URLConnection con=url.openConnection();
InputStream stream=con.getInputStream();
int i;
while((i=stream.read())!=-1)
{
System.out.print((char)i);
}
}
catch(Exception e){}
}
}

3.11 Security in java

The java.security package contains the classes and interfaces that implement the Java security
architecture. These classes can be divided into two broad categories.

First, there are classes that implement access control and prevent untrusted code from performing
sensitive operations.

Second, there are authentication classes that implement message digests and digital signatures and can
authenticate Java classes and other objects.

The central access control class is AccessController; it uses the currently installed Policy object to
decide whether a given class has Permission to access a given system resource.
The Permissions and ProtectionDomain classes are also important pieces of the Java access control
architecture. Figure 1 shows the access control classes of this package.

Figure 1. The access control classes of the java.security package

18 Advanced java Programming


UNIT-4 Networking

The key classes for authentication are MessageDigest and Signature; they compute and verify
cryptographic message digests and digital signatures. These classes use public-key cryptography
techniques and rely on the PublicKey and PrivateKey classes. They also rely on an infrastructure of
related classes, such as SecureRandom for producing cryptographic-strength pseudo-random
numbers, KeyPairGenerator for generating pairs of public and private keys, and KeyStore for
managing a collection of keys and certificates.

3.12 Permission class:

The basic entity that the access controller operates on is a permission object--an instance of
the Permission class (java.security.Permission). The Permission class itself is an abstract class that
represents a particular operation. A permission object can reflect two things. When it is associated
with a class (through a code source and a protection domain), a permission object represents an actual
permission that has been granted to that class. Otherwise, a permission object allows us to ask if we
have a specific permission.

For example, if we construct a permission object that represents access to a file, possession of that
object does not mean that we have permission to access the file. Rather, possession of the object
allows us to ask if we have permission to access the file.

An instance of the Permission class represents one specific permission. A set of permissions--e.g., all
the permissions that are given to classes signed by a particular individual--is represented by an
instance of the Permissions class (java.security.Permissions).

Permission is an abstract class that contains these public methods:

public Permission(String name)

Construct a permission object that represents the desired permission.

public abstract boolean equals(Object o)

Subclasses of the Permission class are required to implement their own test for equality. Often
this is simply done by comparing the name (and actions, if applicable) of the permission.

public abstract int hashCode()

Subclasses of the Permission class are required to implement their own hash code. In order
for the access controller to function correctly, the hash code for a given permission object
must never change during execution of the virtual machine. In addition, permissions that
compare as equal must return the same hash code from this method.

public final String getName()

Return the name that was used to construct this permission.

public abstract String getActions()

Return the canonical form of the actions (if any) that were used to construct this permission.

public String toString()

19 Advanced java Programming


UNIT-4 Networking

The convention for printing a permission is to print in parentheses the class name, the name of
the permission, and the actions.

public abstract boolean implies(Permission p)

This method is one of the keys of the Permission class: it is responsible for determining
whether or not a class that is granted one permission is granted another. This method is
normally responsible for performing wildcard matching, so that, for example, the file
permission /myclasses/- implies the file permission /myclasses/xyz/HRApplet.class. But this
method need not rely on wildcards; permission to write a particular object in a database would
probably imply permission to read that object as well.

public PermissionCollection newPermissionCollection()

Return a permission collection suitable for holding instances of this type of permission. We'll
discuss the topic of permission collections in the next section. This method returns null by
default.

public void checkGuard(Object o)

Call the security manager to see if the permission (i.e., the this variable) has been granted,
generating a SecurityException if the permission has not been granted. The object parameter
of this method is unused. We'll give more details about this method later in this chapter.

3.13 Policy class

The third building block for the access controller is the facility to specify which permissions should
apply to which code sources. We call this global set of permissions the security policy; it is
encapsulated by the Policy class (java.security.Policy).

public abstract class Policy

Establish the security policy for a Java program.

A policy class is constructed as follows:

public Policy()

Create a policy class. The constructor should initialize the policy object according to its
internal rules

Like the security manager, only a single instance of the policy class can be installed in the virtual
machine at any time. However, unlike the security manager, the actual instance of the policy class can
be replaced. These two methods install and retrieve the policy:

public static Policy getPolicy()

Return the currently installed policy object.

public static void setPolicy(Policy p)

Install the given policy object, replacing whatever policy object was previously installed.

20 Advanced java Programming


UNIT-4 Networking

There are two other methods in the Policy class:

public abstract Permissions getPermissions(CodeSource cs)

Create a permissions object that contains the set of permissions that should be granted to
classes that came from the given code source (i.e., loaded from the code source's URL and
signed by the keys in the code source).

public abstract void refresh()

Refresh the policy object. For example, if the initial policy came from a file, re-read the file
and install a new policy object based on the (presumably changed) information from the file.

MCQ’s

1. ______ is a connection-oriented and reliable protocol, ______ is a less reliable protocol.


2. The TCP and UDP protocols use ______ to map incoming data to a particular process running
on a computer.
3. Datagrams are normally sent by ______ protocol.
4. Java uses ______ class representing a server and ______ class representing the client that
uses TCP protocol.
5. ______ is used to wait for accepting client connection requests.
6. Class ______ is used to create a packet of data for UDP protocol.
7. If something goes wrong related to the network, ______ will be thrown when dealing with
TCP/ UDP programming in Java.
8. ______ method is used to instantiate a URLConnection instance.
9. UDP is more reliable than TCP protocol: True or False.
10. The same port number can be reused many times when binding with sockets simultaneously:
True or False.
11. In order to create a client socket connecting to a particular server, the IP address must be
given to the client socket, otherwise, it cannot connect to the server: True or False.
12. Sockets provide an interface for programming networks at the transport layer: True or False.
13. Call Socket.close() method will close the TCP server that socket connects to: True or False.
14. The socket instance does not need to be explicitly closed to release all the resources it
occupies, as the Java Garbage Collection mechanism will do it automatically: True or False
15. The following line of code Socket socket = new Socket(“localhost,” 1254); will create a TCP
server at localhost port 1254: True or False.
16. Java TCP Socket uses the InputStream/OutputStream to read/write data to the network
channel: True or False.
17. Java UDP sends/receives data as raw Java primitive types: True or False.
18. URL Encoding is useful for translating Chinese to English that presents in a particular URL:
True or False.

21 Advanced java Programming

You might also like