0% found this document useful (0 votes)
123 views

Chapter 5 Networking Basics

This document provides an overview of networking and security concepts. It discusses sockets, client/server models, proxy servers, internet addressing, TCP/IP protocols, and the OSI reference model. The key points are that sockets identify endpoints in a network and allow a server to serve multiple clients simultaneously, while client/server and proxy server models define how resources are shared over the network. TCP/IP and UDP are core protocols that enable reliable and unreliable data transmission.

Uploaded by

Atharv Kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

Chapter 5 Networking Basics

This document provides an overview of networking and security concepts. It discusses sockets, client/server models, proxy servers, internet addressing, TCP/IP protocols, and the OSI reference model. The key points are that sockets identify endpoints in a network and allow a server to serve multiple clients simultaneously, while client/server and proxy server models define how resources are shared over the network. TCP/IP and UDP are core protocols that enable reliable and unreliable data transmission.

Uploaded by

Atharv Kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Prashant bhandare

Chapter 4

Networking & Security

-by-
Prof. Bhandare P. S.
SVERI’s COE(Poly), Pandharpur
Syllabus
Prashant bhandare

Unit no & Content Hrs &


name Marks
4.1 Socket Overview: Client/Server ,
Reserved Sockets , Proxy Servers , Internet
Addressing.
4.2 Java and the Net: The Networking
Classes and interfaces.
 4.3 InetAddress : Factory Methods ,
Unit IV –
Networking Instance Methods. 10 hrs
Basics 4.4 TCP/IP Client Sockets : Whois 12 marks
 4.5 URL: Format, The URI Class.
4.6 URLConnection : TCP/IP Server
Sockets .
 4.7 Datagrams : Datagram Packet ,
Datagram Server and Client .
Networking Basics
Prashant bhandare

 At the core of Java’s networking support is


the concept of a socket.

 A socket identifies an endpoint in a network.

 Sockets are at the foundation of modern


networking because a socket allows a single
computer to serve many different clients at
once, as well as to serve many different types
of information.
 This
Prashant bhandare is accomplished through the use of a
port, which is a numbered socket on a
particular machine.

A server process is said to "listen" to a port


until a client connects to it.

 A server is allowed to accept multiple


clients connected to the same port number,
although each session is unique.
 To
Prashant bhandare
manage multiple client connections, a
server process must be multithreaded or have
some other means of multiplexing the
simultaneous I/O.

 Socket communication takes place via a


protocol.

 Internet Protocol (IP) is a low-level routing


protocol that breaks 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
Prashant bhandare Control Protocol (TCP) is a
higher-level protocol that manages to
robustly string together these packets,
sorting and retransmitting them as necessary
to reliably transmit data.

A third protocol, User Datagram Protocol


(UDP), sits next to TCP and can be used
directly to support fast, connectionless,
unreliable transport of packets
The OSI Reference Model
Prashant bhandare

Prashant bhandare A formal OSI - Open System Interconnection -
model has 7 layers but this one shows the essential
layer definitions.

 Each layer has its own standardized protocols and


applications programming interface (API), which
refers to the functions, and their arguments and
return values, called by the next higher layer.

 Internally, the layers can be implemented in


different ways as long as externally they obey the
standard API.
 For example, the Network Layer does not know if the
Prashant bhandare
Physical Layer is Ethernet or a wireless system
because the device drivers respond to the function
calls the same way.

 The Internet refers primarily to the Network Layer


that implements the Internet Protocol (IP) and the
Transport Layer that implements the Transmission
Control Protocol (TCP).

 In fact, we often here people refer to the "TCP/IP"


network rather than calling it the Internet.

 The application layer also includes various protocols,


such as FTP (File Transport Protocol) and HTTP
(Hypertext Transfer Protocol) for the Web, that rely
on the TCP/IP layers.
Socket Overview
Prashant bhandare

 A network socket is a lot like an electrical socket.


Various plugs around the network have a standard
way of delivering their payload.

 Anything that understands 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; as long 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 our house and the rest of
the network. For each kilowatt of power that goes
through that meter, we are billed.
 The bill comes to our address. So even though
Prashant bhandare

the electricity flows freely around the power


grid, all of the sockets in our house have a
particular address.

 The same idea applies to network sockets,


except we talk about TCP/IP packets and IP
addresses rather than electrons and street
addresses.

 Internet Protocol (IP) is a low-level routing


protocol that breaks 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
Prashant bhandare Control Protocol (TCP) is a
higher-level protocol that manages to
robustly string together these packets, sorting
and re-transmitting them as necessary to
reliably transmit our data.

 A third protocol, User Datagram Protocol


(UDP), sits next to TCP and can be used
directly to support fast, connectionless,
unreliable transport of packets.
Client/Server
Prashant bhandare

 A server is anything that has some resource that


can be shared.

 There are compute servers, which provide


computing power; print servers, which manage
a collection of printers; disk servers, which
provide networked disk space; and web servers,
which store web pages.

 A client is simply any other entity that wants to


gain access to a particular server.

 The interaction between client and server is just


like the interaction between a lamp and an
electrical socket.
 The
Prashant bhandare power grid of the house is the server,
and the lamp is a power client.

 The server is a permanently available


resource, while the client is free to unplug
after it is has been served.
 In Berkeley sockets, the notion of a socket
Prashant bhandare

allows a single computer to serve many


different clients at once, as well as serving
many different types of information.

 This feat is managed by the introduction of a


port, which is a numbered socket on a particular
machine.

 A server process is said to listen to a port until a


client connects to it.

 A server is allowed to accept multiple clients


connected to the same port number, although
each session is unique.
Proxy Servers
Prashant bhandare

 A proxy server speaks the client side of a


protocol to another server.

 This is often required when clients have certain


restrictions on which servers they can connect
to.

 Thus, a client would connect to a proxy server,


which did not have such restrictions, and the
proxy server would in turn communicate for the
client.

 A proxy server has the additional ability to


filter certain requests or cache the results of
those requests for future use.

Prashant bhandareA caching proxy HTTP server can help
reduce the bandwidth demands on a local
network’s connection to the Internet.

 When a popular web site is being hit by


hundreds of users, a proxy server can get the
contents of the web server’s popular pages
once, saving expensive internet work
transfers while providing faster access to
those pages to the clients.
Internet Addressing
Prashant bhandare

 Every computer on the Internet has an address.

 An Internet address is a number that uniquely


identifies each computer on the Net.

 Originally, all Internet addresses consisted of


32-bit values.

 This address type was specified by IPv4


(Internet Protocol, version 4).

 However, a new addressing scheme, called


IPv6 (Internet Protocol, version 6) has come
into play.

Prashant bhandare
IPv6 uses a 128-bit value to represent an address.

 Although there are several reasons for and


advantages to IPv6, the main one is that it supports a
much larger address space than does IPv4.

 Fortunately, IPv6 is downwardly compatible with


IPv4.

 Currently, IPv4 is by far the most widely used


scheme, but this situation is likely to change over
time.

 Because of the emerging importance of IPv6, Java 2,


version 1.4 has begun to add support for it.
 There
Prashant bhandare are 32 bits in an IPv4 IP address, and
we often refer to them as a sequence of four
numbers between 0 and 255 separated by
dots (.).

 This makes them easier to remember;


because they are not randomly assigned they
are 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 a class C network, since there are over
two million networks in class C.
Prashant bhandare

Class Range

A 1 – 126*

B 128 – 191

C 192 – 223

D 224 – 239

E 240-255
 The
Prashant bhandare first byte of a class C network is
between 192 and 224, with the last byte
actually identifying an individual computer
among the 256 allowed on a single class C
network.

 This scheme allows for half a billion devices


to live on class C networks.
Domain Naming Service (DNS)
Prashant bhandare

 Just as the four numbers of an IP address


describe a network hierarchy from left to right,
the name of an Internet address, called its
domain name, describes a machine’s location in
a name space, from right to left.

 For example, www.google.com is in the COM


domain (reserved for commercial sites), it is
called Google (after the company name), and
www is the name of the specific computer that
is Google’s web server.

 www corresponds to the rightmost number in


the equivalent IP address.
The Networking Classes and Interfaces
Prashant bhandare

 Java supports TCP/IP both by extending the


already established stream I/O interface and by
adding the features required to build 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.

 The classes contained in the java.net package


are shown here:
Prashant bhandare
Authenticator InetAddress SocketAddress
CacheRequest InetSocketAddress SocketImpl
CacheResponse InterfaceAddress SocketPermission
ContentHandler JarURLConnection StandardSocketOption
CookieHandler MulticastSocket URI
CookieManager NetPermission URL
DatagramPacket NetworkInterface URLClassLoader

DatagramSocket PasswordAuthentication URLConnection

DatagramSocketImpl Proxy URLDecoder


HttpCookie ProxySelector URLEncoder

HttpURLConnection ResponseCache URLPermission (Added by JDK 8.)

IDN SecureCacheResponse URLStreamHandler


Inet4Address ServerSocket
Inet6Address Socket
The java.net package’s interfaces are listed here:
Prashant bhandare

ContentHandlerFactory FileNameMap SocketOptions

CookiePolicy ProtocolFamily URLStreamHandlerFactory

CookieStore SocketImplFactory

DatagramSocketImplFactory SocketOption
InetAddress
Prashant bhandare

 The InetAddress class is used to encapsulate


both the numerical IP address and the domain
name for that address.

 You interact with this class by using the name


of an IP host, which is more convenient and
understandable than its IP address.

 The InetAddress class hides the number inside.

 InetAddress can handle both IPv4 and IPv6


addresses.
Factory Methods
Prashant bhandare

 The InetAddress class has no visible


constructors.

 To create an InetAddress object, you have to


use one of the available factory methods.

 Factory methods are merely a convention


whereby static methods in a class return an
instance of that class.

 This is done in lieu of overloading a


constructor with various parameter lists when
having unique method names makes the results
much clearer.
 Three
Prashant bhandare commonly used InetAddress factory
methods are shown here:

◦ static InetAddress getLocalHost()

◦ static InetAddress getByName(String hostName)

◦ static InetAddress[ ] getAllByName(String hostName)

 The getLocalHost() method simply returns


the InetAddress object that represents the
local host.
 The getByName() method returns
Prashant bhandare
an
InetAddress for a host name passed to it.

 If these methods are unable to resolve the host


name, they throw an
UnknownHostExceptionOn the Internet, it is
common for a single name to be used to
represent several machines.

 In the world of web servers, this is one way to


provide some degree of scaling.

 The getAllByName( ) factory method returns an


array of InetAddresses that represent all of the
addresses that a particular name resolves to.

Prashant bhandareIt will also throw an
UnknownHostException if it can’t resolve
the name to at least one address.

 InetAddress also includes the factory


method getByAddress( ), which takes an IP
address and returns an InetAddress object.
Either an IPv4 or an IPv6 address can be
used.

 The following example prints the addresses


and names of the local machine and two
Internet web sites:
 import java.net.*;
Prashant bhandare

 class InetAddressTest
 {
 public static void main(String args[]) throws
UnknownHostException {
 InetAddress Address = InetAddress.getLocalHost();
 System.out.println(Address);
 Address =
InetAddress.getByName("www.HerbSchildt.com");
 System.out.println(Address);
 InetAddress SW[] =
InetAddress.getAllByName("www.nba.com");
 for (int i=0; i<SW.length; i++)
 System.out.println(SW[i]);
 }
 }
Prashant bhandare
Instance Methods
Prashant bhandare

 The InetAddress class has several other


methods, which can be used on the objects
returned by the methods just discussed.

 Here are some of the more commonly used


methods:
Prashant bhandare
boolean equals(Object
Returns true if this object has the same Internet address as other.
other)

Returns a byte array that represents the object’s IP address in


byte[ ] getAddress( )
network byte order.

Returns a string that represents the host address associated with the
String getHostAddress( )
InetAddress object.

Returns a string that represents the host name associated with the
String getHostName( )
InetAddress object.

boolean Returns true if this address is a multicast address. Otherwise, it


isMulticastAddress( ) returns false.

Returns a string that lists the host name and the IP address for
String toString( )
convenience.
 Internet
Prashant bhandare addresses are looked up in a series of
hierarchically cached servers.

 That means that your local computer might


know a particular name-to-IP-address
mapping automatically, such as for itself and
nearby servers.

 For other names, it may ask a local DNS


server for IP address information.
Prashant bhandare
 If that server doesn’t have a particular address,
it can go to a remote site and ask for it.

 This can continue all the way up to the root


server.

 This process might take a long time, so it is


wise to structure your code so that you cache
IP address information locally rather than look
it up repeatedly.
Inet4Address and Inet6Address
Prashant bhandare

 Java includes support for both IPv4 and IPv6 addresses.


 Because of this, two subclasses of InetAddress were
created: Inet4Address and Inet6Address.

 Inet4Address represents a traditional-style IPv4 address.

 Inet6Address encapsulates a newer IPv6 address.


 Because they are subclasses of InetAddress, an
InetAddress reference can refer to either.

 This is one way that Java was able to add IPv6


functionality without breaking existing code or adding
many more classes.

 For the most part, you can simply use InetAddress when
working with IP addresses because it can accommodate
both styles.
Prashant bhandare

TCP/IP Client Sockets


 TCP/IP sockets are used to implement
reliable, bidirectional, persistent, point-to-
point, 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.
Prashant bhandare
 There
Prashant bhandare are two kinds of TCP sockets in Java.
 One is for servers, and the other is for clients.

 The ServerSocket class is designed to be a


"listener," which waits for clients to connect
before doing anything.

 Thus, ServerSocket is for servers.


 The ClientSocket class is for clients.

 It is designed to connect to server sockets


and initiate protocol exchanges.
 The creation of a Socket object implicitly
Prashant bhandare

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 two constructors used to create client


sockets:
 Socket
Prashant bhandare defines several instance methods. For
example, a Socket can be examined at any
time for the address and port information
associated with it, by use of the following
methods:
 You
Prashant bhandare can gain access to the input and output
streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream( )
methods, as shown here.

 Each can throw an IOException if the socket


has been invalidated by a loss of connection.

 These streams are used exactly like the I/O


streams to send and receive data.
Prashant bhandare

 Several other methods are available,


including connect( ), which allows you to
specify a new connection; isConnected( ),
which returns true if the socket is connected
to a server; isBound( ), which returns true if
the socket is bound to an address; and
isClosed( ), which returns true if the socket
is closed.
Prashant bhandare

 To close a socket, call close( ).

 Closing a socket also closes the I/O streams


associated with the socket.

 Beginning with JDK 7, Socket also implements


AutoCloseable, which means that you can use a
try-with-resources block to manage a socket.

 E.g. Find out which of the first 1,024 ports


seem to be hosting TCP servers on a specified
host
 import java.net.*;
Prashant bhandare

 import java.io.*;
 public class LowPortScanner
 {
 public static void main(String[] args)
 {
 String host = "localhost";
 for (int i = 1; i < 1024; i++)
 {
 try {
 Socket s = new Socket(host, i);
 System.out.println("There is a server on port " + i + " of "
+ host);
 }
 catch (UnknownHostException ex)
Prashant bhandare

{
 System.err.println(ex);
 break;
}
 catch (IOException ex)
{
 // must not be a server on this port
}
 } //end for
 } // end main
 } // end PortScanner
Whois
Prashant bhandare

 The very simple example that follows opens a


connection to a whois port on the InterNIC server,
sends the command-line argument down the socket,
and then prints the data that is returned.

 InterNIC will try to lookup the argument as a


registered Internet domain name, then send back the
IP address and contact information for that site.
 //Demonstrate Sockets.
Prashant bhandare
 import java.net.*;
 import java.io.*;
 class Whois
 {
 public static void main(String args[]) throws Exception
 {
 int c;
 Socket s = new Socket("internic.net", 43);
 InputStream in = s.getInputStream();
 OutputStream out = s.getOutputStream();
 Stringstr=(args.length==0? "osborne.com":args[0])+"\n";
 byte buf[] = str.getBytes();
 out.write(buf);
 while ((c = in.read()) != -1)
 System.out.print((char) c);
 s.close();
 }
 }
TCP/IP Server Sockets
Prashant bhandare

 Java has a different socket class that must be used for


creating server applications.

 The ServerSocket class is used to create servers that


listen for either 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 section develops an operational web
(http) server.

 ServerSockets are quite different from normal


Sockets. When we create a ServerSocket, it will
register itself with the system as having an interest in
client connections.
 The constructors for ServerSocket reflect the port
Prashant bhandare
number that we wish to accept connections on and,
optionally, how long we want the queue for said port
to be.

 The queue length tells the system how many client


connections it can leave pending before it should
simply refuse connections. The default is 50.

 The ServerSocket class contains everything needed to


write servers in Java.

 It has constructors that create new ServerSocket


objects, methods that listen for connections on a
specified port, methods that configure the various
server socket options, and the usual miscellaneous
methods such as toString().
 In
Prashant bhandare 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 port using its
accept( ) method. accept( ) blocks until a
client attempts to make a connection, at
which point accept() returns a Socket object
connecting the client and the server.
 3. Depending on the type of server, either the
Prashant bhandare

Socket's getInputStream() method,


getOutputStream( ) method, or both are called
to get input and output streams that
communicate with the client.

 4. The server and the client interact according


to an agreed-upon protocol until 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.
 Here
Prashant bhandare 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
Prashant bhandare port, int maxQueue,
InetAddress localAddress) throws
IOException

 It creates a server socket on the specified


port with a maximum queue length of
maxQueue.

 On a multi-homed host, local Address


specifies the IP address to which this socket
binds. ServerSocket has a method called
accept( ),
 import java.net.*;
Prashant bhandare
 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
 }
 }
TCP server
Prashant bhandare

 import java.lang.*;
 import java.io.*;
 import java.net.*;

 class Server {
 public static void main(String args[]) {
 String data = "HELLO HOW ARE YOU.....";
 try {
 ServerSocket srvr = new ServerSocket(1234);
 Socket skt = srvr.accept();
 System.out.print("Server has connected!\n");
 PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
 System.out.print("Sending string: '" + data + "'\n");
 out.print(data);
 out.close();
 skt.close();
 srvr.close();
 }
 catch(Exception e) {
 System.out.print("Client not started \n");
 }
 }
 }
TCP Client
Prashant bhandare

 import java.lang.*;
 import java.io.*;
 import java.net.*;
 class Client {
 public static void main(String args[]) {
 try {
 Socket skt = new Socket("localhost", 1234);
 BufferedReader in = new BufferedReader(new
 InputStreamReader(skt.getInputStream()));
 System.out.print("Received string: '");
 System.out.println(in.readLine()); // Read one line and output it
 System.out.print("'\n");
 in.close();
 }
 catch(Exception e) {
 System.out.print("Server not started\n");
 }
 }
 }
URL
Prashant bhandare

 The Web is a loose collection of higher-level protocols and file


formats, all unified in a web browser.

 One of the most important aspects of the Web is that Tim Berners-
Lee devised a scalable way to locate all of the resources of the Net.

 Once you can reliably name anything and everything, it becomes a


very powerful paradigm. The Uniform Resource Locator (URL)
does exactly that.

 The URL provides a reasonably intelligible form to uniquely


identify or address information on the Internet. URLs are
ubiquitous; every browser uses them to identify information on the
Web.

 Within Java’s network class library, the URL class provides a


simple, concise API to access information across the Internet using
URLs.
 A URL specification
Prashant bhandare is based on four
components.

 The first is the protocol to use, separated from


the rest of the locator by a colon (:). Common
protocols are HTTP, FTP, gopher, and file,
although these days almost everything is being
done via HTTP (in fact, most browsers will
proceed correctly if you leave off the "http://"
from your URL specification).

 The second component is the host name or IP


address of the host to use; this is delimited on
the left by double slashes (//) and on the right
by a slash (/) or optionally a colon (:).
 The
Prashant bhandare third 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 HTTP servers will append a file named
index.html or index.htm to URLs that refer
directly to a directory resource.
 Java’s URL class has several constructors; each
Prashant bhandare

can throw a MalformedURLException.

 One commonly used form specifies the URL with


a string that is identical to what you see displayed
in a browser:

 URL(String urlSpecifier) throws MalformedURLException

 The next two forms of the constructor allow you


to break up the URL into its component parts:

 URL(String protocolName, String hostName, int port, String


path )throws MalformedURLException
Prashant bhandare
 URL(String protocolName, String hostName, String
path)throws MalformedURLException

 Another frequently used constructor allows you


to use an existing URL as a reference context
and then create a new URL from that context.
Although this sounds a little contorted, it’s
really quite easy and useful.

 URL(URL urlObj, String urlSpecifier) throws


MalformedURLException

 The following example creates a URL to a page


on HerbSchildt.com and then examines its
properties:
 // Demonstrate URL.
Prashant bhandare
 import java.net.*;
 class URLDemo {
 public static void main(String args[]) throws
MalformedURLException {
 URL hp = new URL(http://www.HerbSchildt.com/WhatsNew");
 System.out.println("Protocol: " + hp.getProtocol());
 System.out.println("Port: " + hp.getPort());
 System.out.println("Host: " + hp.getHost());
 System.out.println("File: " + hp.getFile());
 System.out.println("Ext:" + hp.toExternalForm());
 }
 }
 When you run this, you will get the following output:
 Protocol: http
 Port: -1
 Host: www.HerbSchildt.com
 File: /WhatsNew
 Ext:http://www.HerbSchildt.com/WhatsNew

Prashant bhandare
To access the actual bits or content information
of a URL, create a URLConnection object from
it, using its openConnection( ) method, like
this:

 urlc = url.openConnection()

 openConnection( ) has the following general


form:

◦ URLConnection openConnection( ) throws


IOException

 It returns a URLConnection object associated


with the invoking URL object. Notice that it
may throw an IOException.
URLConnection
Prashant bhandare

 URLConnection is a general-purpose class for


accessing the attributes of a remote resource.

 Once you make a connection to a remote server, you


can use URLConnection to inspect the properties of
the remote object before actually transporting it
locally.

 These attributes are exposed by the HTTP protocol


specification and, as such, only make sense for URL
objects that are using the HTTP protocol.

 URLConnection defines several methods. Here is a


sampling:
Prashant bhandare

Returns the size in bytes of the content


int getContentLength( ) associated with the resource. If the length is
unavailable, –1 is returned

Returns the size in bytes of the content


long getContentLengthLong( ) associated with the resource. If the length is
unavailable, –1 is returned.

Returns the type of content found in the resource.


String getContentType( ) This is the value of the content-type header field.
Returns null if the content type is not available.

Returns the time and date of the response


long getDate( ) represented in terms of milliseconds since
January 1, 1970 GMT

Returns the expiration time and date of the


resource represented in terms of milliseconds
long getExpiration( )
since January 1, 1970 GMT. Zero is returned if
the expiration date is unavailable
 Notice that URLConnection defines several methods that handle
Prashant bhandare

header information.

 A header consists of pairs of keys and values represented as


strings.

 By using getHeaderField( ), you can obtain the value associated


with a header key.
 By calling getHeaderFields( ), you can obtain a map that
contains all of the headers.

 Several standard header fields are available directly through


methods such as getDate() and getContentType( ).

 The single constructor for the URLConnection class is protected:


 protected URLConnection(URL url)
 import java.net.*;
Prashant bhandare
 import java.io.*;
 import java.util.*;
 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: "
Prashant bhandare

 + 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
Datagrams
Prashant bhandare

 TCP includes many complicated algorithms


for dealing with congestion control on
crowded networks, as well as pessimistic
expectations about packet loss.

 This leads to a somewhat inefficient way to


transport data.

 Datagrams provide an alternative.

 Datagrams are bundles of information passed


between machines.
Prashant bhandare
 They are somewhat like a hard throw from a
well-trained but blindfolded catcher to the
third baseman.

 Once the datagram has been released to its


intended target, there is no assurance that it
will arrive or even that someone will be
there to catch it.

 when the datagram is received, there is no


assurance that it hasn’t been damaged in
transit or that whoever sent it is still there to
receive a response.
 Java
Prashant bhandare
implements datagrams on top of the
UDP protocol by using two classes: the
DatagramPacket object is the data container,
while the DatagramSocket is the mechanism
used to send or receive the datagramPackets.
DatagramSocket
Prashant bhandare

 DatagramSocket defines four public


constructors.

 They are shown here:


◦ DatagramSocket( ) throws SocketException
◦ DatagramSocket(int port) throws
SocketException
◦ DatagramSocket(int port, InetAddress
ipAddress) throws SocketException
◦ DatagramSocket(SocketAddress address) throws
SocketException
 The
Prashant bhandare
first creates a DatagramSocket bound to
any unused port on the local computer.

 The second creates a DatagramSocket bound


to the port specified by port.

 The third constructs a DatagramSocket


bound to the specified port and InetAddress.

 The fourth constructs a DatagramSocket


bound to the specified SocketAddress.

Prashant bhandare
SocketAddress is an abstract class that is
implemented by the concrete class
InetSocketAddress.

 InetSocketAddress encapsulates an IP
address with a port number.

 All can throw a SocketException if an error


occurs while creating the socket.
 DatagramSocket
Prashant bhandare
defines many methods.

 Two of the most important are send( ) and


receive( ), which are shown here:
◦ void send(DatagramPacket packet) throws
IOException
◦ void receive(DatagramPacket packet) throws
IOException

 The send( ) method sends a packet to the port


specified by packet.

 The receive( ) method waits for a packet to


be received and returns the result
 DatagramSocket also defines the close( )method, which
Prashant bhandare

closes the socket.


 Beginning with JDK 7, DatagramSocket implements
AutoCloseable, which means that a DatagramSocket can be
managed by a try-with-resources block.
DatagramPacket
Prashant bhandare

 DatagramPacket defines several constructors.

 Four are shown here:


1. DatagramPacket(byte data [ ], int size)
2. DatagramPacket(byte data [ ], int offset, int
size)
3. DatagramPacket(byte data [ ], int size,
InetAddress ipAddress, int port)
4. DatagramPacket(byte data [ ], int offset, int
size, InetAddress ipAddress, int port)

Prashant bhandare The first constructor specifies a buffer that will receive
data and the size of a packet.

 It is used for receiving data over a DatagramSocket.

 The second form allows you to specify an offset into the


buffer at which data will be stored.

 The third form specifies a target address and port, which


are used by a DatagramSocket to determine where the
data in the packet will be sent.

 The fourth form transmits packets beginning at the


specified offset into the data.

 Think of the first two forms as building an "in box," and


the second two forms as stuffing and addressing an
envelope
 DatagramPacket defines several methods, including
Prashant bhandare

those shown here, that give access to the address


and port number of a packet, as well as the raw data
and its length.
Prashant bhandare Returns the address of the source (for datagrams
InetAddress getAddress( ) being received) or destination (for datagrams
being sent).
Returns the byte array of data contained in the
byte[ ] getData( ) datagram. Mostly used to retrieve data from
the datagram after it has been received.
Returns the length of the valid data contained
in the byte array that would be returned from
int getLength( )
the getData( ) method. This may not equal the
length of the whole byte array
int getOffset( ) Returns the starting index of the data.
int getPort( ) Returns the port number.
void setAddress(InetAddress Sets the address to which a packet will be sent.
ipAddress) The address is specified by ipAddress.
Sets the data to data, the offset to zero, and the
void setData(byte[ ] data)
length to number of bytes in data.
void setData(byte[ ] data, int Sets the data to data, the offset to idx, and the
idx, int size) length to size.
void setLength(int size) Sets the length of the packet to size.
void setPort(int port) Sets the port to port.
e.g.
Prashant bhandare

 //DSender.java
 import java.net.*;
 public class DSender{
 public static void main(String[] args) throws Exception {
 DatagramSocket ds = new DatagramSocket();
 String str = "Welcome java";
 InetAddress ip = InetAddress.getByName("127.0.0.1");

 DatagramPacket dp = new DatagramPacket(str.getBytes(),
str.length(), ip, 3000);
 ds.send(dp);
 ds.close();
 }
 }
Prashant bhandare
 import java.net.*;
 public class DReceiver{
 public static void main(String[] args) throws Exception
{
 DatagramSocket ds = new DatagramSocket(3000);
 byte[] buf = new byte[1024];
 DatagramPacket dp = new DatagramPacket(buf, 1024);
 ds.receive(dp);
 String str = new String(dp.getData(), 0, dp.getLength());

 System.out.println(str);
 ds.close();
 }
 }

You might also like