Chapter 3
Chapter 3
Chapter – 03 Marks: 16
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.
Page 1
Advance Java Programming (17625)
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.
Page 3
Advance Java Programming (17625)
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.
Page 4
Advance Java Programming (17625)
TCP UDP
Acronym for User Datagram Protocol or Universal
Acronym for Transmission Control Protocol
Datagram 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 does Flow Control. UDP does not have an option for flow control
TCP does error checking UDP does error checking, but no recovery options.
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
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.
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.
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.
Page 8
Advance Java Programming (17625)
Page 9
Advance Java Programming (17625)
Page 10
Advance Java Programming (17625)
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)
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.
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)
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
}
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.
Page 20
Advance Java Programming (17625)
pw.close();
br.close();
s.close();
}
}
Output:
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
System.out.println("Protocol :"+u.getProtocol());
System.out.println("Port :"+u.getPort());
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)
import java.io.*;
import java.util.*;
import java.net.*;
Page 25
Advance Java Programming (17625)
URLConnection u2;
u2=u1.openConnection();
System.out.println("Content Type:"+u2.getContentType());
System.out.println("Content Length:"+u2.getContentLength());
Output:
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( )
Page 27
Advance Java Programming (17625)
Page 28
Advance Java Programming (17625)
Example:
import java.net.*;
import java.io.*;
importjava.util.*;
Page 29
Advance Java Programming (17625)
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
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)
Page 33
Advance Java Programming (17625)
Page 34
Advance Java Programming (17625)
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
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)
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
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)
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)
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