0% found this document useful (0 votes)
33 views52 pages

Chapter 3

This document covers advanced Java programming concepts related to networking and security, including the basics of networking, the InetAddress class, TCP/IP sockets, and URL handling. It explains the significance of protocols like TCP and UDP, the OSI model, and the role of proxy servers and IP addressing. Additionally, it introduces Java's networking classes and interfaces, emphasizing their utility in developing networked applications.

Uploaded by

birhadepranusha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views52 pages

Chapter 3

This document covers advanced Java programming concepts related to networking and security, including the basics of networking, the InetAddress class, TCP/IP sockets, and URL handling. It explains the significance of protocols like TCP and UDP, the OSI model, and the role of proxy servers and IP addressing. Additionally, it introduces Java's networking classes and interfaces, emphasizing their utility in developing networked applications.

Uploaded by

birhadepranusha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Advance Java Programming (17625)

Chapter – 03 Marks: 16

Networking & Security

3.1 Basics of Networking


Socket, IP, TCP, UDP, Proxy Server, Internet Addressing
3.2 The InetAddress Class
Factory methods
Instance methods
3.3 TCP/IP Sockets
Socket, Server Socket, methods
3.4 URL
URL Connection, http, URL Connection methods, creating & using
TCP/IP client & server
3.5 Security with Java: Theoretical introduction to java.security
Package
Permission class
Policy class

Introduction:
The java programming is also used for developing network application. So the Java
programming language, more appropriate for writing networked programs than, say, C++ or
FORTRAN.Whatmakes Java a good language for networking are the classes defined in
thejava.net package. These networking classes encapsulate the socket paradigm pioneered
inthe Berkeley Software Distribution (BSD) from the University of California atBerkeley. No
discussion of Internet networking libraries would be completewithout a brief recounting of
the history of UNIX and BSD sockets.

3.1 Basics of Networking


Ken Thompson and Dennis Ritchie developed UNIX in concert with the C language at Bell
Telephone Laboratories, in 1969. For many years, thedevelopment of UNIX remained in Bell
Labs and in a few universities andresearch facilities that had the DEC-PDP machines it was
designed to be run on.In 1978, Bill Joy was leading a project at Cal Berkeley to add many
newfeatures to UNIX, such as virtual memory and full-screen display capabilities.

Page 1
Advance Java Programming (17625)

By early 1984, just as Bill was leaving to found Sun Microsystems, he


shipped4.2BSD,commonly known as Berkeley UNIX. 4.2 BSD came with a fast filesystem,
reliable signals, inter-process communication, and, most important,networking. The
networking support first found in 4.2 eventually became the defacto standard for the Internet.
Berkeley’s implementation of TCP/IP remainsthe primary standard for communications
within the Internet. The socketparadigm for inter-process and network communication has
also been widelyadopted outside of Berkeley. Even Windows and the Macintosh started
talkingBerkeley sockets in the late 80s.

The OSI Reference Model:

Figure 3.1: OSI Reference Model

A formal OSI - Open System Interconnection - model has 7 layers butthis one shows
the essential layer definitions. Each layer has its ownstandardized protocols and applications
programming interface (API), whichrefers to the functions, and their arguments and return
values, called by thenext higher layer. Internally, the layers can be implemented in different
waysas long as externally they obey the standard API.
For example, the Network Layer does not know if the Physical Layer isEthernet or a
wireless system because the device drivers respond to thefunction calls the same way. The
Internet refers primarily to the Network Layerthat implements the Internet Protocol (IP) and
the Transport Layer thatimplements the Transmission Control Protocol (TCP). In fact, we
often herepeople refer to the "TCP/IP" network rather than calling it the Internet.
The application layer also includes various protocols, such as FTP (FileTransport Protocol)
and HTTP (Hypertext Transfer Protocol) for the Web, thatrely on the TCP/IP layers. Most
users never look below the application layer.Most application programmers never work
below the TCP/IP layers.

Page 2
Advance Java Programming (17625)

Socket:
A network socket is a lot like an electrical socket. Various plugs aroundthe network
have a standard way of delivering their payload. Anything thatunderstands the standard
protocol can plug into the socket and communicate.With electrical sockets, it doesn’t matter
if you plug in a lamp or a toaster; aslong as they are expecting 50Hz, 115-volt electricity, the
devices will work.Think how our electric bill is created. There is a meter some where
between ourhouse and the rest of the network. For each kilowatt of power that goesthrough
that meter, we are billed. The bill comes to our address. So eventhough the electricity flows
freely around the power grid, all of the sockets inour house have a particular address. The
same idea applies to network sockets,except we talk about TCP/IP packets and IP addresses
rather than electronsand street addresses.
Internet Protocol (IP) is a low-level routing protocol thatbreaks data into small
packets and sends them to an address across a network,which does not guarantee to deliver
said packets to the destination.Transmission Control Protocol (TCP) is a higher-level protocol
that manages torobustly string together these packets, sorting and re-transmitting them as
necessary to reliably transmit our data. A third protocol, User DatagramProtocol (UDP), sits
next to TCP and can be used directly to support fast,connectionless, unreliable transport of
packets client. The server is a permanently available resource, while the client is free
tounplug after it is has been served.

Figure 3.2: Client-Server Communication


In Berkeley sockets, the notion of a socket allows a single computer toserve many
different clients at once, as well as serving many different types ofinformation. This feat is

Page 3
Advance Java Programming (17625)

managed by the introduction of a port, which is anumbered socket on a particular machine. A


server process is said to listen to aport until a client connects to it. A server is allowed to
accept multiple clientsconnected to the same port number, although each session is unique.
Tomanage multiple client connections, a server process must be multithreaded orhave some
other means of multiplexing the simultaneous I/O.

IP Address:
Internet Protocol Address (or IP Address) is an unique address that computing devices
use to identify itself and communicate with other devices in the Internet Protocol network.
Any device connected to the IP network must have an unique IP address within its network.
An IP address is analogous to a street address or telephone number in that it is used to
uniquely identify a network device to deliver mail message, or call ("view") a website.
For Eg: 192.168.1.1

TCP:
Abbreviation of Transmission Control Protocol, and pronounced as separate letters. TCP is
one of the main protocols in TCP/IP networks. Whereas the IP protocol deals only with
packets, TCP enables two hosts to establish a connection and exchange streams of data. TCP
guarantees delivery of data and also guarantees that packets will be delivered in the same
order in which they were sent.

UDP(User Datagram Protocol):


It is a communications protocol that offers a limited amount of service when
messages are exchanged between computers in a network that uses the Internet Protocol (IP).
UDP is an alternative to the Transmission Control Protocol (TCP) and, together with IP, is
sometimes referred to as UDP/IP.

Page 4
Advance Java Programming (17625)

Difference between TCP and UDP protocols:

TCP UDP
Acronym for User Datagram Protocol or Universal
Acronym for Transmission Control Protocol
Datagram Protocol

TCP is a connection-oriented protocol. UDP is a connectionless protocol.

TCP is suited for applications that require high UDP is suitable for applications that need fast,
reliability. efficient transmission, such as games,video etc.
TCP rearranges data packets in the order UDP does not rearranges data packets in the order
specified. specified.
UDP is faster because there is no error-checking
The speed for TCP is slower than UDP.
for packets.
There is absolute guarantee that the data There is no guarantee that the messages or packets
transferred. sent would reach at all.

TCP header size is 20 bytes UDP Header size is 8 bytes.

TCP is heavy-weight. UDP is lightweight.

TCP does Flow Control. UDP does not have an option for flow control

TCP does error checking UDP does error checking, but no recovery options.

Acknowledgement segments No Acknowledgment

Reserved Sockets:
A socket is one of the most fundamental technologies of computer networking.
Sockets allow applications to communicate using standard mechanisms built into network
hardware and operating systems. Although network software may seem to be a relatively new
"Web" phenomenon, socket technology actually has been employed for roughly two decades.
Once connected, a higher-level protocol ensues, which is dependent onwhich port we are
using. TCP/IP reserves the lower 1,024 ports for specificprotocols. Many of these will seem
familiar to us if we have spent any timesurfing the Internet. Port number 21 is for FTP, 23 is
for Telnet, 25 is for email,79 is for finger, 80 is for HTTP, 119 is for net-news and the list
goes on. Itis up to each protocol to determine how a client should interact with the port

Introduction to networking ports:


In computer networking of connection-based communication port is like a
medium through which, an application establish a connection with another application by

Page 5
Advance Java Programming (17625)

binding a socket by a port number. Addressing the information and the port no., accompanied
the data transfer over the network. The Ports are used by TCP and UDP to deliver the data to
the right application, are identified by a 16-bit number present in the header of a data packet.
Ports are typically used to map data to a particular process running on a client. If we consider
a letter (data packet) sent to a particular apartment (IP) with house no. (port no), at this
timethe port no. is the most important part for the delivery of the letter. In order for the
delivery to work, the sender needs to include an house number along with the address to
ensure the letter gets to the right destination.

Reserved port numbers:

Service Port No.

Echo 7

Daytime 13

ftp 21

telnet 23

smtp 25

finger 79

http 80

pop3 110

If we consider the range of the port numbers, there are 0 to 65,535 portsavailable. The
port numbers ranging from 0 - 1023 are reserved ports or we can say that are restricted ports.
All the 0 to 1023 ports are reserved for use by well-known services such as FTP, telnet and
http and other system services. These ports are called well-known ports.
Example:
HTTP is the protocol that web browser and server use to transfer hypertext pages and
images. It is quite a simple protocol for a works. When a client request a file from an http
server,an action known as hit it simply prints the name of the file in a special format to a
predefined port and reader back the content of the file. The server also responds with a status
code number to tell the client whether the request can be fulfilled.

Page 6
Advance Java Programming (17625)

Proxy Servers:
A proxy server speaks the client side of a protocol to another server. Thisis often required
when clients have certain restrictions on which servers theycan connect to. Thus, a client
would connect to a proxy server, which did nothave such restrictions, and the proxy server
would in turn communicate for theclient.

Figure 3.3: Proxy Server

A proxy server has the additional ability to filter certain requests orcache the results of
those requests for future use. A caching proxy HTTP server can help reduce the bandwidth
demands on a local network’s connection to theInternet. When a popular web site is being hit
by hundreds of users, a proxyserver can get the contents of the web server’s popular pages
once, savingexpensive internet work transfers while providing faster access to those pagesto
the clients.

Internet Addressing:
Every computer on the Internet has an address. An Internet address is anumber that
uniquely identifies each computer on the Net. Originally, allInternet addresses consisted of
32-bit values. This address type was specifiedby IPv4 (Internet Protocol, version 4).
However, a new addressing scheme,called IPv6 (Internet Protocol, version 6) has come into
play. IPv6 uses a 128-bit value to represent an address. Although there are several reasons for
andadvantages to IPv6, the main one is that it supports a much larger addressspace than does
IPv4. Fortunately, IPv6 is downwardly compatible with IPv4.Currently, IPv4 is by far the
most widely used scheme, but this situation islikely to change over time.Because of the

Page 7
Advance Java Programming (17625)

emerging importance of IPv6, Java 2, version 1.4 hasbegun to add support for it. However, at
the time of this writing, IPv6 is notsupported by all environments. Furthermore, for the next
few years, IPv4 willcontinue to be the dominant form of addressing. As mentioned, IPv4 is,
loosely,a subset of IPv6, and the material contained in this chapter is largely applicableto
both forms of addressing.
There are 32 bits in an IPv4 IP address, and we often refer to them as asequence of
four numbers between 0 and 255 separated by dots (.). Thismakes them easier to remember;
because they are not randomly assigned theyare hierarchically assigned. The first few bits
define which class of network,lettered A, B, C, D, or E, the address represents. Most Internet
users are on aclass C network, since there are over two million networks in class C. The
firstbyte of a class C network is between 192 and 224, with the last byte actuallyidentifying
an individual computer among the 256 allowed on a single class Cnetwork. This scheme
allows for half a billion devices to live on class Cnetworks.

Domain Naming Service (DNS):


The Internet wouldn’t be a very friendly place to navigate if everyone hadto refer to
their addresses as numbers. For example, it is difficult to imagineseeing http://192.9.9.1/ at
the bottom of an advertisement. Thankfully, aclearing house exists for a parallel hierarchy of
names to go with all thesenumbers. It is called the Domain Naming Service (DNS). Just as
the fournumbers of an IP address describe a network hierarchy from left to right, thename of
an Internet address, called its domain name, describes a machine’slocation in a name space,
from right to left. For example, www.google.com is inthe COM domain (reserved for
commercial sites), it is called Google (after thecompany name), and www is the name of the
specific computer that is Google’sweb server. www corresponds to the rightmost number in
the equivalent IPaddress.

Java and the Net:


Now that the stage has been set, let’s take a look at how Java relates toall of these
network concepts. Java supports TCP/IP both by extending thealready established stream I/O
interface and by adding the features required tobuild I/O objects across the network. Java
supports both the TCP and UDP protocol families. TCP is used for reliable stream-based I/O
across the network.UDP supports a simpler, hence faster, point-to-point datagram-oriented
model.

Page 8
Advance Java Programming (17625)

The Networking Classes and Interfaces:


The classes contained in the java.net package are listed here:
Authenticator InetSocketAddress SocketImpl
ContentHandler JarURLConnection SocketPermission
DatagramPacket MulticastSocket
URIDatagramSocketNetPermission URLDatagramSocketImpl
NetworkInterfaceURLClassLoader HttpURLConnection
PasswordAuthentication

URLConnection InetAddress ServerSocket


URLDecoder Inet4Address Socket URLEncoder
Inet6Address SocketAddress RLStreamHandler
Some of these classes are to support the new IPv6 addressing scheme.Others provide
some added flexibility to the original java.net package. Java 2,version 1.4 also added
functionality, such as support for the new I/O classes, toseveral of the preexisting networking
classes. The java.net package’s interfacesare listed here:
ContentHandlerFactory SocketImplFactory URLStreamHandlerFactory
FileNameMap SocketOptions DatagramSocketImplFactory

Page 9
Advance Java Programming (17625)

Page 10
Advance Java Programming (17625)

3.2 The InetAddress Class:


Whether we are making a phone call, sending mail, or establishing aconnection across
the Internet, addresses are fundamental. The InetAddressclass is used to encapsulate both the
numerical IP address and the domainname for that address. We interact with this class by
using the name of an IPhost, which is more convenient and understandable than its IP
address. TheInetAddress class hides the number inside. As of Java 2, version 1.4,InetAddress
can handle both IPv4 and IPv6 addresses. This discussion assumes IPv4

Factory Methods:
The InetAddress class has no visible constructors. To create anInetAddress object, we
have to use one of the available factory methods.Factory methods are merely a convention
whereby static methods in a classreturn an instance of that class. This is done in lieu of
overloading a constructorwith various parameter lists when having unique method names
makes theresults much clearer. Three commonly used InetAddress factory methods areshown
here.static InetAddress getLocalHost( ) throws UnknownHostExceptionstatic InetAddress get By
Name (String host Name) throws UnknownHostExceptionstatic InetAddress[ ] getAllByName(String
hostName) throws UnknownHostExceptionThe getLocalHost( ) method simply returns the
InetAddress object thatrepresents the local host. The getByName( ) method returns an InetAddress
fora host name passed to it. If these methods are unable to resolve the hostname, they throw an
UnknownHostException.On the Internet, it is common for a single name to be used to
representseveral machines. In the world of web servers, this is one way to provide somedegree of
scaling.The getAllByName( ) factory method returns an array ofInetAddresses that represent all of the
addresses that a particular nameresolves to. It will also throw an UnknownHostException if it can’t
resolve thename to at least one address. Java2, version1.4 also includes the factorymethod
getByAddress(), which takes an IP address and returns an InetAddressobject. Either an IPv4 or an
IPv6 address can be used. The following exampleprints the addresses and names of the local machine
and two well-knownInternet web sites:
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[])
throws UnknownHostException
{

Page 11
Advance Java Programming (17625)

InetAddress Address = InetAddress.getLocalHost();


System.out.println(Address);
Address = InetAddress.getByName("google.com");
System.out.println(Address);
InetAddress SW[ ] = InetAddress.getAllByName("www.yahoo.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
Output:
itdept-server/192.168.1.75
google.com/209.85.171.100
www.yahoo.com/87.248.113.14

Instance Methods:
The InetAddress class also has several other methods, which can be usedon the
objects returned by the methods just discussed. Here are some of themost commonly
used.boolean equals(Object other)It returns true if this object has the same Internet address as
other.byte[ ] getAddress( )
It returns a byte array that represents the object’s Internet address innetwork byte order.
String getHostAddress( )
It returns a string that represents the host address associated with theInetAddress object.
String getHostName( )
It returns a string that represents the host name associated with theInetAddress object.
boolean isMulticastAddress( )
It returns true if this Internet address is a multicast address. Otherwise, itreturns false.
String toString( )
It returns a string that lists the host name and the IP address forconvenience.
Internet addresses are looked up in a series of hierarchically cachedservers. That
means that our local computer might know a particular name-to-IP-address mapping
automatically, such as for itself and nearby servers. Forother names, it may ask a local DNS
server for IP address information. If thatserver doesn’t have a particular address, it can go to a
remote site and ask forit. This can continue all the way up to the root server, called

Page 12
Advance Java Programming (17625)

InterNIC(internic.net). This process might take a long time, so it is wise to structure ourcode
so that we cache IP address information locally rather than look it uprepeatedly.

3.3 TCP/IP Sockets:


Socket:
A socket is a connection between two hosts. It can perform seven basic operations:
• Connect to a remote machine
• Send data
• Receive data
• Close a connection
• Bind to a port
• Listen for incoming data
• Accept connections from remote machines on the bound port

TCP/IP Client Sockets:


TCP/IP sockets are used to implement t reliable, bidirectional, persistent, point-to-
point, and stream-based connections between hosts on the Internet. A socket can be used to
connect Java’s I/O system to other programs that may reside either on the local machine or on
any other machine on the Internet.

Fig. Clients and servers, Sockets and ServerSockets


Applets may only establish socket connections back to the host from which the applet
was downloaded. This restriction exists because it would be dangerous for applets loaded
through a firewall to have access to any arbitrary machine. There are two kinds of TCP
sockets in Java. One is for servers, and the other is for clients. The ServerSocket class is

Page 13
Advance Java Programming (17625)

designed to be a listener, which waits for clients to connect before doing anything. The
Socket class isdesigned to connect to server sockets and initiate protocol exchanges. The
creation of a Socket object implicitly establishes a connection between the client and server.
There are no methods or constructors that explicitly expose the details of establishing that
connection. Here are twoconstructors used to create client sockets:Socket(String hostName,
int port) throws UnknownHostException, IOException
Creates a socket connecting the local host to the named host and port; can throw an
UnknownHostException or an IOException.
Socket(InetAddress ipAddress, int port) throws UnknownHostException,
IOException
Creates a socket using a preexisting InetAddress object and a port; can throw an
IOException. A socket can be examined at any time for the address and port information
associated with it, by use of the following methods:
InetAddress getInetAddress( )
It returns the InetAddress associated with the Socket object.
intgetPort( )
It returns the remote port to which this Socket object is connected.
int getLocalPort( )
It returns the local port to which this Socket object is connected.
Once the Socket object has been created, it can also be examined to gain access to the
input and output streams associated with it. Each of these methods can throw an IOException
if the sockets have been invalidated by a loss of connection on the Net. These streams are
used exactly like the other I/O streams to send and receive data.
InputStream getInputStream( )
This returns the InputStream associated with the invoking socket.
OutputStreamgetOutputStream( )
This returns the OutputStream associated with the invoking socket.
Find out which of the first 1,024 ports seem to be hosting TCP servers on a specified host
import java.net.*;
import java.io.*;
public class LowPortScanner
{
public static void main(String[] args)

Page 14
Advance Java Programming (17625)

{
String host = "localhost";
for (int i = 1; i< 1024; i++)
{
try {
Socket s = new Socket(host, i);
Server Socket, methods
System.out.println("There is a server on port " + i
+ " of " + host);
}
catch (UnknownHostException ex)
{
System.err.println(ex);
break;
}
catch (IOException ex)
{
// must not be a server on this port
}
} // end for
} // end main
} // end PortScanner
Here's the output this program produces on local host. Results will vary,depending on which
ports are occupied. As a rule, more ports will be occupiedon a Unix workstation than on a PC
or a Mac:
java LowPortScanner
There is a server on port 21 of localhost
There is a server on port 80 of localhost
There is a server on port 110 of localhost
There is a server on port 135 of localhost
There is a server on port 443 of localhost

Page 15
Advance Java Programming (17625)

TCP/IP Server Sockets:


Java has a different socket class that must be used for creating serverapplications. The
ServerSocket class is used to create servers that listen foreither local or remote client
programs to connect to them on published ports.Since the Web is driving most of the activity
on the Internet, this sectiondevelops an operational web (http) server.ServerSockets are quite
different from normal Sockets. When we create aServerSocket, it will register itself with the
system as having an interest inclient connections. The constructors for ServerSocket reflect
the port numberthat we wish to accept connections on and, optionally, how long we want
thequeue for said port to be. The queue length tells the system how many clientconnections it
can leave pending before it should simply refuse connections.The default is 50.
The ServerSocket class contains everything needed to write servers inJava. It has
constructors that create new ServerSocket objects, methods thatlisten for connections on a
specified port, methods that configure the variousserver socket options, and the usual
miscellaneous methods such as toString().In Java, the basic life cycle of a server program is:
1. A new ServerSocket is created on a particular port using a ServerSocket()constructor.
2. The ServerSocket listens for incoming connection attempts on that portusing its
accept( ) method. accept( ) blocks until a client attempts tomake a connection, at
which point accept( ) returns a Socket objectconnecting the client and the server.
3. Depending on the type of server, either the Socket's getInputStream()method,
getOutputStream( ) method, or both are called to get input andoutput streams that
communicate with the client.
4. The server and the client interact according to an agreed-upon protocoluntil it is time
to close the connection.
5. The server, the client, or both close the connection.
6. The server returns to step 2 and waits for the next connection.
The constructors might throw an IOException under adverse conditions.Here are the
constructors:
ServerSocket(int port) throws BindException, IOException
It creates server socket on the specified port with a queue length of 50.
ServerSocket(int port, int maxQueue) throws BindException,IOException
This creates a server socket on the specified port with a maximum queue length of
maxQueue.
ServerSocket(int port, int maxQueue, InetAddress localAddress)throws IOException

Page 16
Advance Java Programming (17625)

It creates a server socket on the specified port with a maximum queuelength of maxQueue.
On a multi-homed host, local Address specifies the IPaddress to which this socket binds.
ServerSocket has a method called accept( ),which is a blocking call that will wait for a client
to initiate communications, andthen return with a normal Socket that is then used for
communication with theclient.
Scanner for the server ports:
import java.net.*;
import java.io.*;
public class LocalPortScanner
{
public static void main(String[] args)
{
for (int port = 1; port <= 65535; port++)
{
try
{
// the next line will fail and drop into the catch block if
// there is already a server running on the port
ServerSocket server = new ServerSocket(port);
}
catch (IOException ex)
{
System.out.println("There is a server on port " + port+ ".");
} // end catch
} // end for
}

Accepting and Closing Connections:


A ServerSocket customarily operates in a loop that repeatedly acceptsconnections.
Each pass through the loop invokes the accept( ) method. Thisreturns a Socket object
representing the connection between the remote clientand the local server. Interaction with
the client takes place through this Socketobject. When the transaction is finished, the server
should invoke the Socketobject's close() method. If the client closes the connection while the

Page 17
Advance Java Programming (17625)

server isstill operating, the input and/or output streams that connect the server to theclient
throw an InterruptedIOException on the next read or write.
In eithercase, the server should then get ready to process the next incomingconnection.
However, when the server needs to shut down and not process anyfurther incoming
connections, we should invoke the ServerSocket object'sclose( ) method.public Socket
accept( ) throws IOException
When server setup is done and we're ready to accept a connection, callthe
ServerSocket'saccept() method. This method "blocks"; that is, it stops theflow of execution
and waits until a client connects. When a client does connect,the accept( ) method returns a
Socket object. We use the streams returned bythis Socket's getInputStream( ) and
getOutputStream( ) methods to
communicate with the client. For example:
ServerSocket server = new ServerSocket(5776);
while (true)
{
Socket connection = server.accept( );
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream( ));
out.write("You've connected to this server. Bye-bye now.\r\n");
connection.close( );
}
If we don't want the program to halt while it waits for a connection, putthe call to
accept( ) in a separate thread.When exception handling is added, the code becomes somewhat
moreconvoluted. It's important to distinguish between exceptions that shouldprobably shut
down the server and log an error message, and exceptions thatshould just close that active
connection. Exceptions thrown by accept( ) or theinput and output streams generally should
not shut down the server. Mostother exceptions probably should. To do this, we’ll need to
nest our try blocks.
Finally, most servers will want to make sure that all sockets they acceptare closed
when they're finished. Even if the protocol specifies that clients areresponsible for closing
connections, clients do not always strictly adhere to theprotocol. The call to close( ) also has
to be wrapped in a try block that catchesan IOException. However, if we do catch an
IOException when closing thesocket, ignore it. It just means that the client closed the socket
before theserver could. Here's a slightly more realistic example:

Page 18
Advance Java Programming (17625)

try
{
ServerSocket server = new ServerSocket(5776);
while (true)
{
Socket connection = server.accept( );
try
{
Writer out= new OutputStreamWriter(connection.getOutputStream( ));
out.write("You've connected to this server. Bye-bye now.");
out.flush( );
connection.close( );
}
catch (IOException ex)
{
// This tends to be a transitory error for this one connection;
// e.g. the client broke the connection early. Consequently,
// we don't want to break the loop or print an error message.
// However, we might choose to log this exception in an error log.
}
finally
{
// Guarantee that sockets are closed when complete.
try
{
if (connection != null) connection.close( );
}
catch (IOException ex) {}
}
}
catch (IOException ex)
{
System.err.println(ex);

Page 19
Advance Java Programming (17625)

}
public void close( ) throws IOException
If we're finished with a server socket, we should close it, especially if theprogram is
going to continue to run for some time. This frees up the port forother programs that may
wish to use it. Closing a ServerSocket should not beconfused with closing a Socket. Closing a
ServerSocket frees a port on the localhost, allowing another server to bind to the port; it also
breaks all currentlyopen sockets that the ServerSocket has accepted.
public InetAddress getInetAddress( )
This method returns the address being used by the server (the localhost). If the local host has
a single IP address (as most do), this is the addressreturned by InetAddress.getLocalHost( ).
If the local host has more than one IPaddress, the specific address returned is one of the host's
IP addresses. Wecan't predict which address we will get. For example:
ServerSocket httpd = new ServerSocket(80);
InetAddress ia = httpd.getInetAddress( );
If the ServerSocket has not yet bound to a network interface, this methodreturns null.
public int getLocalPort( )
The ServerSocket constructors allow us to listen on an unspecified port bypassing 0
for the port number. This method lets us find out what port we'relistening on.

//Program to demonstrate a Client Socket


import java.net.*;
import java.io.*;
classSampleClient
{
public static void main(String args[]) throws Exception
{
Socket s = new Socket("localhost",9999);
PrintWriterpw = new PrintWriter(s.getOutputStream(),true);
pw.println("Hello ");
BufferedReaderbr = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println(str);

Page 20
Advance Java Programming (17625)

pw.close();
br.close();
s.close();
}
}
Output:

//Program to demonstrate a Server Socket


import java.net.*;
import java.io.*;
class SampleServer{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(9999);
while(true)
{
System.out.println("Server is waiting for client requests");
Socket cs = ss.accept();
System.out.println("Got the socket connection with the client");
BufferedReaderbr = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
String s = br.readLine();
PrintWriterpw = new PrintWriter(cs.getOutputStream(),true);
pw.println(s);
br.close();
pw.close();

Page 21
Advance Java Programming (17625)

cs.close();
}// end of while
}// end of main
}// end of class
Output:

3.4 URL:-
The Web is a loose collection of higher-level protocols and file formats, al unified in a
web browser. way to locate all of the resources of theNet. Once we can reliably name
anything and everything, it becomes a verypowerful paradigm. The Uniform Resource
Locator (URL) does exactly that.The URL provides a reasonably intelligible form to uniquely
identify oraddress information on the Internet. URLs are ubiquitous; every browser usesthem
to identify information on the Web.
WithinJava’s network class library, the URL class provides a simple, concise API
toaccess information across the Internet using URLs.Two examples of URLs
arehttp://www.rediff.com/and http://www.rediff.com:80/index.htm/.
A URL specification is based on fourcomponents. The first is the protocol to use,
separated from the rest of thelocator by a colon (:). Common protocols are http, ftp, gopher,
and file although these days almost everything is being done via HTTP (in fact, mostbrowsers
will proceed correctly if we leave off the http:// from our URLspecification).
The second component is the host name or IP address of thehost to use; this is delimited on
the left by double slashes (//) and on the rightby a slash (/) or optionally a colon (:). The third

Page 22
Advance Java Programming (17625)

component, the port number,is an optional parameter, delimited on the left from the host
name by a colon(:) and on the right by a slash (/). (It defaults to port 80, the predefined HTTP
port; thus:80 is redundant.) The fourth part is the actual file path. Most HTTPservers will
append a file named index.html or index.htm to URLs that referdirectly to a directory
resource.
Java’s URL class has several constructors,and each can throw a MalformedURLException.
URL(String urlSpecifier)
The next two forms of the constructor allow you to break up the URL intoits component
parts:
URL(String protName, String hostName, int port, String path)
URL(String protName, String hostName, String path)
In the following example, we create a URL to cric-info’s news page andthen examine its
properties:
// Program to make use of URL Class

import java.net.*;

class URLDemo

public static void main(String args[]) throws MalformedURLException

URL u= new URL("http://www.msbte.com/msbte/curriculum_search");

System.out.println("Protocol :"+u.getProtocol());

System.out.println("Host Name :"+u.getHost());

System.out.println("Port :"+u.getPort());

System.out.println("File Path :"+u.getFile());

System.out.println("Complete URL :"+u.toExternalForm());

Page 23
Advance Java Programming (17625)

Output:

Notice that the port is -1; this means that one was not explicitly set. Nowthat we have
created a URL object, we want to retrieve the data associatedwith it. To access the actual bits
or content information of a URL,we create aURLConnection object from it, using its
openConnection( ) method, like this:
url.openConnection()
openConnection( ) has the following general form:
URLConnection openConnection( )
It returns a URLConnection object associated with the invoking URLobject. It may throw an
IOException.

URL Connection:
URLConnection is an abstract class that represents an active connectionto a resource
specified by a URL. The URLConnection class has two different butrelated purposes. First, it
provides more control over the interaction with aserver (especially an HTTP server) than the
URL class. With a URLConnection,we can inspect the header sent by the server and respond
accordingly. We canset the header fields used in the client request. We can use a
URLConnection todownload binary files. Finally, a URLConnection lets us send data back to
a webserver with POST or PUT and use other HTTP request methods.A program that uses
the URLConnection class directly follows this basicsequence of steps:
1. Construct a URL object.
2. Invoke the URL object's openConnection( ) method to retrieve a URLConnection
object for that URL.
3. Configure the URLConnection.
4. Read the header fields.
5. Get an input stream and read data.
6. Get an output stream and write data.

Page 24
Advance Java Programming (17625)

7. Close the connection.


We don't always perform all these steps. For instance, if the default setupfor a particular
kind of URL is acceptable, then we're likely to skip step 3. If weonly want the data from the
server and don't care about any meta-information,or if the protocol doesn't provide any meta-
information, we'll skip step 4. If weonly want to receive data from the server but not send
data to the server, we'llskip step 6. Depending on the protocol, steps 5 and 6 may be reversed
orinterlaced.
The single constructor for the URLConnection class is protected:protected
URLConnection(URL url)
Consequently, unless we're sub-classing URLConnection to handle a newkind of URL
(that is, writing a protocol handler), we can only get a reference toone of these objects
through the openConnection( ) methods of the URL andURLStreamHandler classes. For
example:
try
{
URL u = new URL("http://www.greenpeace.org/");
URLConnection uc = u.openConnection( );
}
catch (MalformedURLException ex)
{
System.err.println(ex);
}
catch (IOException ex)
{
System.err.println(ex);
}

// Prgoram to demonsrate the URL Connection class

import java.io.*;

import java.util.*;

import java.net.*;

public class URLConnectionDemo

Page 25
Advance Java Programming (17625)

public static void main(String args[]) throws IOException

URL u1=new URL("http://www.msbte.com/msbte/curriculum_search");

URLConnection u2;

u2=u1.openConnection();

System.out.println("Date:"+ new Date(u2.getDate()));

System.out.println("Content Type:"+u2.getContentType());

System.out.println("Expiration:"+ new Date(u2.getExpiration()));

System.out.println("last Modified="+new Date(u2.getLastModified()));

System.out.println("Content Length:"+u2.getContentLength());

Output:

Reading Data from a Server:


Here is the minimal set of steps needed to retrieve data from a URL usinga
URLConnection object:
1. Construct a URL object.
2. Invoke the URL object's openConnection( ) method to retrieve a URLConnection
object for that URL.
3. Invoke the URLConnection'sgetInputStream( ) method.

Page 26
Advance Java Programming (17625)

4. Read from the input stream using the usual stream API.
5. The getInputStream() method returns a generic InputStream that letsyou read and
parse the data that the server sends.
6. public InputStream getInputStream( )

Example- Download a web page with a URLConnection:


import java.net.*;
import java.io.*;
public class SourceViewer2
{
public static void main (String[] args)
{
if (args.length > 0)
{
try
{
//Open the URLConnection for reading
URL u = new URL(args[0]);
URLConnection uc = u.openConnection( );
InputStream raw = uc.getInputStream( );
InputStream buffer = new BufferedInputStream(raw);
// chain the InputStream to a Reader
Reader r = new InputStreamReader(buffer);
int c;
while ((c = r.read( )) != -1)
{
System.out.print((char) c);
}
}
catch (MalformedURLException ex)
{
System.err.println(args[0] + " is not a parseable URL");
}

Page 27
Advance Java Programming (17625)

catch (IOException ex)


{
System.err.println(ex);
}
} // end if
} // end main
} // end SourceViewer2
The differences between URL and URLConnection aren't apparent with just a simple input
stream as in this example. The biggest differences between the two classes are:
1. URLConnection provides access to the HTTP header.
2. URLConnection can configure the request parameters sent to the server.
3. URLConnection can write data to the server as well as read data from theserver.

Reading the Header:


HTTP servers provide a substantial amount of information in the headerthat precedes
each response. For example, here's a typical HTTP headerreturned by an Apache web server:
HTTP/1.1 200 OK
Date: Mon, 18 Oct 1999 20:06:48 GMT
Server: Apache/1.3.4 (Unix) PHP/3.0.6 mod_perl/1.17
Last-Modified: Mon, 18 Oct 1999 12:58:21 GMT
ETag: "1e05f2-89bb-380b196d"
Accept-Ranges: bytes
Content-Length: 35259
Connection: close
Content-Type: text/html
1. Public String getContentType( )
This method returns the MIME content type of the data. It relies on theweb server to
send a valid content type.
For Example:
text/plain, image/gif, application/xml, and image/jpeg.
Content-type: text/html; charset=UTF-8
or
Content-Type: text/xml; charset=iso-2022-jp

Page 28
Advance Java Programming (17625)

2. Public int getContentLength( )


The getContentLength( ) method tells us how many bytes there are in thecontent.
Many servers send Content-length headers only when they'retransferring a binary file, not
when transferring a text file. If there is noContent-length header, getContentLength() returns -
1. The method throws noexceptions. It is used when we need to know exactly how many
bytes to read
or when we need to create a buffer large enough to hold the data in advance.
3. Public long getDate( )
The getDate( ) method returns a long that tells us when the documentwas sent, in
milliseconds since midnight, Greenwich Mean Time (GMT), January1, 1970. We can convert
it to a java.util.Date. For example:
Date documentSent = new Date(uc.getDate( ));
This is the time the document was sent as seen from the server; it maynot agree with
the time on our local machine. If the HTTP header does notinclude a Date field, getDate( )
returns 0.
4. Public long getExpiration( )
Some documents have server-based expiration dates that indicate whenthe document
should be deleted from the cache and reloaded from the server.getExpiration( ) is very similar
to getDate( ), differing only in how the returnvalue is interpreted. It returns a long indicating
the number of millisecondsafter 12:00 A.M., GMT, January 1, 1970, at which point the
document expires.If the HTTP header does not include an Expiration field, getExpiration( )
returns0, which means 12:00 A.M., GMT, January 1, 1970. The only reasonableinterpretation
of this date is that the document does not expire and can remainin the cache indefinitely.
5.public long getLastModified( )
The final date method, getLastModified( ), returns the date on which thedocument
was last modified. Again, the date is given as the number ofmilliseconds since midnight,
GMT, January 1, 1970. If the HTTP header doesnot include a Last-modified field (and many
don't), this method returns 0.

Example:
import java.net.*;
import java.io.*;
importjava.util.*;

Page 29
Advance Java Programming (17625)

public class HeaderViewer


{
public static void main(String args[])
{
try
{
URL u = new URL("http://www.rediffmail.com/index.html");
URLConnection uc = u.openConnection( );
System.out.println("Content-type: " +uc.getContentType( ));
System.out.println("Content-encoding: "+ uc.getContentEncoding( ));
System.out.println("Date: " + new Date(uc.getDate( )));
System.out.println("Last modified: "+ new Date(uc.getLastModified( )));
System.out.println("Expiration date: "+ new Date(uc.getExpiration( )));
System.out.println("Content-length: " +uc.getContentLength( ));
} // end try
catch (MalformedURLException ex)
{
System.out.println("I can't understand this URL...");
}
catch (IOException ex)
{
System.err.println(ex);
}
System.out.println( );
} // end main
} // end HeaderViewer

Sample output:
Content-type: text/html
Content-encoding: null
Date: Mon Oct 18 13:54:52 PDT 1999
Last modified: Sat Oct 16 07:54:02 PDT 1999
Expiration date: Wed Dec 31 16:00:00 PST 1969

Page 30
Advance Java Programming (17625)

Content-length: -1
Sample output for: http://www.oreilly.com/graphics/space.gif
Content-type: image/gif
Content-encoding: null
Date: Mon Oct 18 14:00:07 PDT 1999
Last modified: Thu Jan 09 12:05:11 PST 1997
Expiration date: Wed Dec 31 16:00:00 PST 1969
Content-length: 57

TCP/IP Client/Server chatting:-


In TCP/IP Client/Server chatting program we need to create two programs first is Client
program & other is Server program. To run these program we have to open two command
prompts for client & server. First run the server and then client program as server has to
responds to the client.
//Client Program
import java.net.*;
import java.io.*;
public class ChatClient
{
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("localhost",2000);
BufferedReader sin=new BufferedReader(new InputStreamReader
(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();

Page 31
Advance Java Programming (17625)

System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") )
break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
Output:

// Server Program
import java.net.*;
import java.io.*;
public class ChatServer
{
public static void main(String args[ ]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();
BufferedReader cin=new BufferedReader(new InputStreamReader
(sk.getInputStream()));

Page 32
Advance Java Programming (17625)

PrintStream cout=new PrintStream(sk.getOutputStream());


BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System.out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}
Output:

Page 33
Advance Java Programming (17625)

3.5 Security with Java:


The Java language is designed to be type-safe and easy to use. It provides automatic
memory management, garbage collection, and range-checking on arrays. This reduces the
overall programming burden placed The Java language is designed to be type-safe and easy
to use. It provides automatic memory management on developers, leading to fewer subtle
programming errors and to safer, more robust code.
In addition, the Java language defines different access modifiers that can be assigned to Java
classes, methods, and fields, enabling developers to restrict access to their class
implementations as appropriate. Specifically, the language defines four distinct access levels:
private, protected, public, and, if unspecified, package. The most open access specifier is
public—access is allowed to anyone. The most restrictive modifier is private—access is not
allowed outside the particular class in which the private member (a method, for example) is
defined. The protected modifier allows access to any subclass, or to other classes within the
same package. Package-level access only allows access to classes within the same package.
3.5.1 Theoretical introduction to java.security package:
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. Figureshows the access control classes of this package.

Page 34
Advance Java Programming (17625)

Figure: Hierarchy of java security package


Permission class:
When Java code is loaded by a class loader into the Java runtime, the class loader
automatically associates the following information with that code:
• Where the code was loaded from
• Who signed the code (if anyone)
• Default permissions granted to the code
This information is associated with the code regardless of whether the code is downloaded
over an untrusted network (e.g., an applet) or loaded from the filesystem (e.g., a local
application). The location from which the code was loaded is represented by a URL, the code
signer is represented by the signer’s certificate chain, and default permissions are represented
by java.security.Permission objects.
The default permissions automatically granted to downloaded code include the ability to
make network connections back to the host from which it originated. The default permissions
automatically granted to code loaded from the local filesystem include the ability to read files
from the directory it came from, and also from subdirectories of that directory. Note that the
identity of the user executing the code is not available at class loading time. It is the
responsibility of application code to authenticate the end user if necessary. Once the user
has been authenticated, the application can dynamically associate that user with executing
code by invoking the doAs method in the javax.security.auth.Subject class.

Page 35
Advance Java Programming (17625)

Policy class:
As mentioned earlier, a limited set of default permissions are granted to code by class
loaders. Administrators have the ability to flexibly manage additional code permissions via a
security policy. The Java platform encapsulates the notion of a security policy in the
java.security.Policy class. There is only one Policy object installed into the Java runtime at
any given time. The basic responsibility of the Policy object is to determine whether access to
a protected resource is permitted to code (characterized by where it was loaded from, who
signed it, and who is executing it). How a Policy object makes this determination is
implementation-dependent.
For example, it may consult a database containing authorization data, or it may
contact another service. The Java platform includes a default Policy implementation that
reads its authorization data from one or more ASCII (UTF-8) files configured in the security
properties file. These policy files contain the exact sets of permissions granted to code—
specifically, the exact sets of permissions granted to code loaded from particular locations,
signed by particular entities, and executing as particular users. The policy entries in each file
must conform to a documented proprietary syntax, and may be composed via a simple text
editor or the graphical policy tool utility.

Summary:
This chapter introduces the basic concepts of Java network programming. Java
network programming contains various networking classes which help us to write Java
network applications. This chapeter gives more imphasis on network classes to create
network based application. The InetAddress class will provide the more information about
the Host computer in the Client/Server network. This chapter also introduces about Socket
programming, which gives you the classes like Socket, ServerSocket for creating sockets
during network application development. The URL & URL connections class elloborate how
we will get the more information about URL specified by the user. This chapter introduces
Java security packages which may help us to write Java security applications.

Page 36
Advance Java Programming (17625)

Sample Question

1. To manage multiple client connections a server process must be -------------


a) Multiported.
b) Effective.
c) Efficient.
d) Multithreaded.
ANSWER: d
2. Nowadays we are using ----------- version of Internet addressing
a) IPV2.
b) IPV3.
c) IPV4.
d) IPV5.
ANSWER: c
3. Default value for Server Socket constructor is ----------
a) 50.
b) 60.
c) 70.
d) 80.
ANSWER: a
4. Datagram provides an alternative for -----------
a) IP.
b) TCP.
c) TCP/IP.
d) UDP.
ANSWER: c
5. If sockets have been invalidated ---------- are used to send and receive data.
a) IP stream.
b) TCP.
c) UDP.
d) I/O stream.
ANSWER: d

Page 37
Advance Java Programming (17625)

6. Which datagram method returns the byte array of data contained in the datagram?
a) InetAddressgetAddress().
b) intgetPort().
c) byte[] getData().
d) byte[] getAddress().
ANSWER: c
7. ________method returns the length of data contained in the byte array.
a) getLength().
b) getLengthOf().
c) getDataLength().
d) getDataLengthOf().
ANSWER: a
8. What does URL stands for?
a) Uniform Resource Locator
b) Uniform Resource Latch
c) Universal Resource Locator
d) Universal Resource Latch
ANSWER: a
9.Which of these exception is thrown by URL class’s constructors?
a) URLNotFound
b) URLSourceNotFound
c) MalformedURLException
d) URLNotFoundException
ANSWER: c
10. Which of these methods is used to know host of an URL?
a) host()
b) getHost()
c) GetHost()
d) gethost()
ANSWER: b
11.Which of these methods is used to know the full URL of an URL object?
a) fullHost()
b) getHost()

Page 38
Advance Java Programming (17625)

c) ExternalForm()
d) toExternalForm()
ANSWER: d
12.Which of these class is used to access actual bits or content information of a URL?
a) URL
b) URLDecoder
c) URLConnection
d) All of the mentioned
ANSWER: d
13. Which of these class is used to encapsulate IP address and DNS?
a) DatagramPacket
b) URL
c) InetAddress
d) ContentHandler
ANSWER: c
14. What is the output of this program?
import java.net.*;
class networking
{
public static void main(String[] args) throws MalformedURLException {
URL obj = new URL("http://www.sanfoundry.com/javamcq");
System.out.print(obj.getProtocol());
}
}
a) http
b) https
c) www
d) com
ANSWER: a
15. What is the output of this program?
import java.net.*;
class networking
{

Page 39
Advance Java Programming (17625)

public static void main(String[] args) throws MalformedURLException {


URL obj = new URL("http://www.sanfoundry.com/javamcq");
System.out.print(obj.getPort());
}
}

a) 1
b) 0
c) -1
d) garbage value
ANSWER: c
16. What is the output of this program?
import java.net.*;
class networking
{
public static void main(String[] args) throws MalformedURLException {
URL obj = new URL("http://www.sanfoundry.com/javamcq");
System.out.print(obj.getHost());
}
}

a) sanfoundry
b) sanfoundry.com
c) www.sanfoundry.com
d) http://www.sanfoundry.com/javamcq
ANSWER: c

17. What is the output of this program?


import java.net.*;
class networking
{
public static void main(String[] args) throws MalformedURLException {
URL obj = new URL("http://www.sanfoundry.com/javamcq");

Page 40
Advance Java Programming (17625)

System.out.print(obj.toExternalForm());
}
}

a) sanfoundry
b) sanfoundry.com
c) www.sanfoundry.com

d) d)http://www.sanfoundry.com/javamcq
ANSWER: d
18. Which of these is wrapper around everything associated with a reply from an http
server?
a) HTTP
b) HttpResponse
c) Httpserver
d) httpserver
ANSWER: a
19. Which of these tranfer protocol must be used so that URL can be accessed by
URLConnection class object?
a) http
b) https
c) Any Protocol can be used
d) None of the mentioned
ANSWER: a
20. Which of these methods is used to know when was the URL last modified?
a) LastModified()
b) getLastModified()
c) GetLastModified()
d) getlastModified()()
ANSWER: b
21. Which of these methods is used to know the type of content used in the URL?
a) ContentType()
b) contentType()

Page 41
Advance Java Programming (17625)

c) getContentType()
d) GetContentType()
ANSWER: c
22. Which of these data member of HttpResponse class is used to store the response from a
http server?
a) status
b) address
c) statusResponse
d) statusCode
ANSWER: d
23. What is the output of this program?
import java.net.*;
class networking
{
public static void main(String[] args) throws Exception
{
URL obj = new URL("http://www.sanfoundry.com/javamcq");
URLConnection obj1 = obj.openConnection();
intlen = obj1.getContentLength();
System.out.print(len);
}
}
Note: Host URL is having length of content 127.

a) 126
b) 127
c) Compilation Error
d) Runtime Error
ANSWER: b
24. What is the output of this program?
import java.net.*;
class networking
{

Page 42
Advance Java Programming (17625)

public static void main(String[] args) throws Exception


{
URL obj = new URL("http://www.sanfoundry.com/javamcq");
URLConnection obj1 = obj.openConnection();
System.out.print(obj1.getLastModified);
}
}
Note: Host URL was last modified on july 18 tuesday2013 .

a) july
b) 18-6-2013
c) Tue 18 Jun 2013
d) Tue Jun 18 2013
ANSWER: d
25. Which of these methods of httpd class is used to read data from the stream?
a) getDta()
b) GetResponse()
c) getStream()
d) getRawRequest()
ANSWER: d
26. Which of these method of httpd class is used to get report on each hit to HTTP server?
a) log()
b) logEntry()
c) logHttpd()
d) logResponse()
ANSWER: b
27. Which of these method is used to find a URL from the cache of httpd?
a) findfromCache()
b) findFromCache()
c) serveFromCache()
d) getFromCache()
ANSWER: c

Page 43
Advance Java Programming (17625)

28.Which of these variables stores the number of hits that are successfully served out of
cache?
a) hits
b) hitstocache
c) hits_to_cache
d) hits.to.cache
ANSWER: d
29.Which of these class is used for operating on request from the client to the server?
a) http
b) httpDecoder
c) httpConnection
d) httpd
ANSWER: d
30. Which of these method of httpd class is used to write UrlCacheEntry object into local
disk?
a) writeDiskCache()
b) writetoDisk()
c) writeCache()
d) writeDiskEntry()
ANSWER: a
31. Which of these method is used to start a server thread?
a) run()
b) start()
c) runThread()
d) startThread()
ANSWER: a
32. Which of these method is called when http daemon is acting like a normal web server?
a) Handle()
b) HandleGet()
c) handleGet()
d) Handleget()
ANSWER: c
33. What is the output of this program?

Page 44
Advance Java Programming (17625)

import java.net.*;
class networking
{
public static void main(String[] args) throws UnknownHostException
{
InetAddress obj1 = InetAddress.getByName("cisco.com");
System.out.print(obj1.getHostName());
}
}

a) cisco
b) cisco.com
c) www.cisco.com
d) None of the mentioned
ANSWER: b
34. Which of these is a bundle of information passed between machines?
a) MIME
b) cache
c) Datagrams
d) DatagramSocket
ANSWER: __
35. Which of these class is necessary to implement datagrams?
a) DatagramPacket
b) DatagramSocket
c) Both of the mentioned
d) None of the mentioned
ANSWER: c
36. Which of these method of DatagramPacket is used to find the port number?
a) port()
b) getPort()
c) findPort()
d) recievePort()
ANSWER: a

Page 45
Advance Java Programming (17625)

37. Which of these method of DatagramPacket is used to obtain the byte array of data
contained in a datagram?
a) getData()
b) getBytes()
c) getArray()
d) recieveBytes()
ANSWER: a
38. Which of these method of DatagramPacket is used to find the length of byte array?
a) getnumber()
b) length()
c) Length()
d) getLength()
ANSWER: d
39. Which of these class must be used to send a datatgram packets over a connection?
a) InetAdress
b) DatagramPacket
c) DatagramSocket
d) All of the mentioned
ANSWER: d
40.What is the output of this program?
import java.net.*;
class networking
{
public static void main(String[] args) throws Exception
{
URL obj = new URL("http://www.sanfoundry.com/javamcq");
URLConnection obj1 = obj.openConnection();
System.out.print(obj1.getContentType());
}
}
Note: Host URL is written in html and simple text.
a) html
b) text

Page 46
Advance Java Programming (17625)

c) html/text
d) text/html
ANSWER: d
41. Which of these method of DatagramPacket class is used to find the destination
address?
a) findAddress()
b) getAddress()
c) Address()
d) whois()
ANSWER: b
42. Which of these is a return type of getAddress method of DatagramPacket class?
a) DatagramPacket
b) DatagramSocket
c) InetAddress
d) ServerSocket
ANSWER: c
43. GET methods are great for sending ....................amounts of information that you do not
mind having visible in a URL.
a) negligible
b) huge
c) small
d) both and b
ANSWER: c
44. What is sent to the user via HTTP, invoked using the HTTP protocol on the user's
computer, and run on the user's computer as an application?
a) A Java application
b) A Java applet
c) A Java servlet
d) None of the above is correct.
ANSWER: b
45. Which of these interface abstractes the output of messages from httpd?
a) LogMessage
b) LogResponse

Page 47
Advance Java Programming (17625)

c) Httpdserver
d) httpdResponse
ANSWER: a
46. Which of these class is used to create servers that listen for either local or remote client
programs?
a) httpServer
b) ServerSockets
c) MimeHeader
d) HttpResponse
ANSWER: b
47. Which of these is a standard for communicating multimedia content over email?
a) HTTP
b) HTTPS
c) MIME
d) HTTPD
ANSWER: c
48.Which of these methods is used to make raw MIME formatted string?
a) parse()
b) toString()
c) getString()
d) parseString()
ANSWER: a
49. Which of these class is used for operating on request from the client to the server?
a) http
b) httpDecoder
c) httpConnection
d) httpd
ANSWER: d
50. Which of these method of MimeHeader is used to return the string equivalent of the
values stores on MimeHeader?
a) string()
b) toString()
c) convertString()

Page 48
Advance Java Programming (17625)

d) getString()
ANSWER: b
51. Which of these is an instance variable of class httpd?
a) port
b) cache
c) log
d) All of the mentioned
ANSWER: d
52. Which of these is an instance variable of httpd that is a Hashtable?
a) port
b) cache
c) log
d) stopFlag
ANSWER: c
53. What is the output of this program?
import java.net.*;
class networking
{
public static void main(String[] args) throws UnknownHostException
{
InetAddress obj1 = InetAddress.getByName("sanfoundary.com");
InetAddress obj2 = InetAddress.getByName("sanfoundary.com");
boolean x = obj1.equals(obj2);
System.out.print(x);
}
}
a) 0
b) 1
c) true
d) false
Answer:c

Page 49
Advance Java Programming (17625)

54. Show some networking terminologies given below?


a. IP Address
b. Protocol
c. MAC Address
d. All mentioned above
ANSWER: d) All mentioned above
55. TCP,FTP,Telnet,SMTP,POP etc. are examples of ?
a. Socket
b. IP Address
c. Protocol
d. MAC Address
ANSWER: C) Protocol
56. Which classes are used for connection-oriented socket programming?
a. Socket
b. ServerSocket
c. Both A & B
d. None of the above

ANSWER: c) Both a & b


57. Which class can be used to create a server socket. This object is used to establish
communication with the clients?
a. ServerSocket
b. Socket
c. Both A & B
d. None of the above
ANSWER: a) ServerSocket
58. Which methods are commonly used in ServerSocket class?
a. public OutputStreamgetOutputStream()
b. public Socket accept()
c. public synchronized void close()
d. None of the above
ANSWER: B) public Socket accept()

Page 50
Advance Java Programming (17625)

59. The web server then responds back to the _____________ accordingly:
a) Web browser
b) Web server
c) Server
d) All of these
ANSWER: a
60. It specifies the name of host issuing request:
a) REMOTE_HOST
b) REMOTE HOST
c) Remote_host
d) None of these
Answer: a
61. It specifies the name of user issuing request:
a) REMOTE_USER
b) REMOTE USER
c) Remote_user
d) None of these
Answer: a
62. It specifies the address of the system of the user issue the request:
a) REMOTE ADDR
b) Remote_Addr
c) Remote addr
d) REMOTE_ADDR
Answer: d
63. It specifies the request method used by the browser:
a. REQUEST METHOD
b. REQUEST_METHOD
c. Request}_method
d. None of these
Answer: b
64. __________ is a factory method which returns an array of addresses.
a) getLocalhost.
b) getByName.

Page 51
Advance Java Programming (17625)

c) getAllByName.
d) getByAddress.
ANSWER: c
65. _______protocol supports fast point to point datagram oriented model.
a) TCP/IP.
b) UDP.
c) TCP.
d) IP.
ANSWER: c
66. The constructor which is used to create client socket is ____________.
a) Socket(Inet Address, IP Address, int port).
b) ServerSocket(int port).
c) ServerSocket(int port, intmaxQueue).
d) Socket(Inet Address, int port).
ANSWER: a
67._____________ are bundles of information passed between machines.
a) Datagrams.
b) Sockets.
c) Client Sockets.
d) Datagram packet.
ANSWER: a
68.The constructor which is used in server socket is______________.
a) Socket (Inet Address, int port, IP Address).
b) Server Socket (int port).
c) Server Socket (intmaxQueue, Inet Address).
d) Server Socket(intmaxQueue, Inet Address localAddress).
ANSWER: b
69._______ method is used to examine the address and port information by the socket.
a) getInetAddress().
b) localPort().
c) getPort().
d) getLength().
ANSWER: b

Page 52

You might also like