4. Unit Outcomes
Use the InetAddress class to know the IP address of the give host name
Use URLConnection classes to read and write data to the specified resources
referred by the given URL
Develop program for client/server communication through TCP/IP Server sockets
for the given problem
Write a program to illustrate the Client/Server communication using datagram
protocol for the given problem
5. Networking means communication or exchange of information between two or
more devices/programs/processes over the network or internet
Basic Concepts in Networking
Some basic and important concepts in networking are :
Socket (network socket)
Client/Server
Proxy Servers
Internet Addressing
Domain Name Service (DNS)
inform
ation/data
network
6. Socket
A socket is one endpoint of a two-way communication link between two programs
running on the network
A socket has a port number linked with it
client
program
Server
program port (socket)
port (socket)
network
Server machine
Client machine
7. Internet Protocol (IP) is a low level protocol that divided data into small packets
and sends them to a device with particular IP address across a network
Socket
IP protocol doesn't give the guarantee that your data packets will be send to the
destination or not
Transmission Control Protocol (TCP) is a higher level protocol which gives you
guarantee that your data will be deliver to the destination
TCP protocol combines, sorts and resends the data packets to the destination
User Datagram Protocol (UDP) is also a higher level protocol that directly and
quickly transmit your data
UDP is connectionless and unreliable protocol, it doesn't give guarantee that your
data will reach the destination or not
9. TCP/IP protocols delivers data (packets) to particular machine, but which
application will use that data is decided by higher-level protocols and port numbers
Socket
TCP/IP reserves the lower 1024 ports for specific protocols
Like 21 port number -> FTP protocol
23 port number -> Telnet protocol
25 port number -> email
79 port number -> finger
80 port number -> HTTP protocol
119 port number -> netnews, and so on
10. How to find list of connections and port numbers in windows ?
Follow the following steps to find list of connections and port numbers in windows
1) Open the command prompt by typing "command prompt" in search
box or by typing "cmd" in run box
2) Type "ipconfig" command in command prompt
3) Then type "netstat -a" command in command prompt to get list of
connections and port numbers
11. How to find list of connections and port numbers in windows ?
Output
12. HTTP Protocol
HTTP protocol is used by web browsers and servers for transferring hypertext web
pages and images over the internet
In HTTP protocol when a client requests a file from the server, it prints name of file
in special format to a predefined port number, this is known as hit action
The client also reads back the content (data) of file from the port number
The server responds to the client with a status code - which tells whether client
request for data can be satisfied or not
13. HTTP Protocol
Server Client
Listens to port 80 Connects to port 80
Accepts the connection Writes
"GET/computer_department.
html
HTTP/1.0nn"
Reads upto second end of line (n)
Sees that GET is a known command
andthat HTTP/1.0 is a valid protocol version
Reads a local file called computer_department.html
Writes "HTTP/1.0 200 OKnn"
Copies the content of file into socket
Hangs up
"200" means file is coming
Reads the content of file and
displays it
Hangs up
14. Client and Server
Servers are hardware/software or combination of both, which has some resources
which can be shared with other computers
Various types of resources are provided by different servers like :
compute servers - provides
computational power
print servers - provides
collection of printers
disk servers - provides
disk space over network
web servers - provides
and stores web pages
15. Client and Server
A client is any device that wants to use the resources provided by the server
The resources provided by the server are always available and client can use it
whenever it requires
A single compute/server can serve many clients at a same time due to concept of
port
A port is socket with particular number on a machine
A server can accept multiple clients on a same port number, but each client will
have different unique session
To handle multiple client connection a server must use multithreaded programming
17. Proxy Servers
A proxy server is a server that acts as a client for some other server
Proxy server sits between client and actual server
When the client wants some information or web pages from the server then it will
not directly communicate with server
The client will first communicate with proxy server for data, then proxy server will
forward the request to actual server and give back the data to the client
Proxy server also filters requests for security
Proxy server can cache (store) the web pages , which can be accessed without going
to the actual server, reducing time, and bandwith
18. Proxy Servers
client
proxy server
actual server
1) client requests data
2) proxy server forwards request
3) server sends data to proxy server
4) forwards data to client
19. Internet Addressing
Every computer that is connected to an internet has an address, which is called as
IP address
Internet address (IP address) uniquely identifies each computer on the internet
There are to versions of IP protocols :
IPv4 ( Internet
Protocol, Version 4 )
IPv6 ( Internet
Protocol, Version 6 )
20. IPv4 Address
IPv4 address is 32 bit long
IPv4 address is sequence of four numbers,where each number is between 0 to 255,
these four numbers are separated by dot (.) ex: 192.168.1.141
IP address is divided into two parts - one part specifies the network prefix and the
other part identifies the host identifier
There are five classes of IPv4 addresses as follow :
Class A
address
Class B
address
Class C
address
Class D
address
Class E
address
21. IPv4 Address
Class A address -
In class A address the first 8 bits or first dotted decimal is a network part and
remaining 24 bits represent host part of a network
There are 128 possible class A networks, starting address is 0.0.0.0
ex: 3.121.152.106
host part (24 bits)network part (8 bits)
Class B address -
In class B address the first 16 bits is a network part and remaining 16 bits
represent host part of a network
There are 16384 possible class B networks, starting address is 128.0.0.0
ex: 131.59.121.119
host part (16 bits)network part (16 bits)
22. IPv4 Address
Class C address -
In class C address the first 24 bits is a network part and remaining 8 bits represent
host part of a network
There are 2097152 possible class C networks, starting address is 192.0.0.0
ex: 192.168.1.144
host part (24 bits)network part (8 bits)
Class D address -
In class D address all the 32 bits are used for network part, no bits are used for
host part
Class D address are called as multicast address and used to uniquely identify
,multicast network, starting address 224.0.0.0
ex: 239.255.255.255
network part ( all 32 bits )
23. IPv4 Address
Class E address -
Class E addresses have first 4 bit network address set to 1
The range of class E address is from 240.0.0.0 to 255.255.255.255
ex: 243.161.87.28
Addresses of class E are reserved and it's use is not defined
Addresses 255.255.255.255 is used as broadcast address
24. IPv4 addresses are limited and as more and more devices are getting connected to
the internet, IPv4 addresses are not enough to cover all devices
As IPv4 addresses are limited, IPv6 addresses are introduced which provides more IP
addresses
IPv6 Address
IPv6 addresses are 128 bits long
In future more IPv6 addresses will be used and slowly it will replace IPv4 addresses
IPv6 is downward compatible with IPv4
IPv6 128 bits
IPv4 32 bits
25. Domain Name Service (DNS)
It is very difficult to remember numerical IP addresses (ex 192.168.122.167) than
domain names (www.google.co.in)
Domain Name Service (DNS) is a naming system that translates domain name into
numerical IP addresses
Four numbers of IP address describes network heirarchy from left to right
In same way domain name decribes machine's location from right to left
192.168.121.133
www.facebook.com
26. How DNS works ?
A5
A4
LTR
Face Down
Ready
Error
Start / Stop
Give me IP address of www.amazon.com
IP address of server is 192.171.1.129
connects server at IP 192.171.1.129
gets data from amazon server
amazon server
DNS server
Client
1
2
3
4
27. Networking Classes and Interfaces in Java
Java supports both TCP and UDP protocols
Java uses TCP for reliable stream-based I/O across the network
UDP is used for more faster point-to-point datagram transfer
Classes and interfaces used for networking are present in java.net package
Following is the list of classes in java.net package
Authenticator
ContenHandler
DatagramPacket
DatagramSocket
DatagramSocketImpl
HttpURLConnection
InetAddress
Inet4Address
Inet6Address
InetSocketAddress
JarURLConnection
MulticastSocket
28. Networking Classes and Interfaces in Java
Following is the list of classes in java.net package
NetPermission
NetworkInterface
PasswordAuthentication
ServerSocket
Socket
SocketAddress
SocketImpl
URLConnection
URI
URL
URLClassLoader
URLDecoder
SocketPermission URLEncoder
URLStreamHandler
29. Networking Classes and Interfaces in Java
Following is the list of interfaces in java.net package
ContentHandlerFactory
FileNameMap
SocketImplFactory URLStreamHandlerFactry
SocketOptions DatagramSocketImplFactory
30. InetAddress class
The InetAddress class contains both numerical IP address (ex: 192.168.1.5) and
domain name for addresses (ex: www.gpgadchiroli.ac.in)
We interact with this class by using host name rather than IP address
InetAddress class hides the numerical IP address inside
InetAddress class has no visible constructors
For creating objects of InetAddress class Factory methods are used
Factory methods are functions which are used for creating objects instead of
directly calling the constructor (without 'new' operator)
31. InetAddress class
Some of the factory methods are as below :
static InetAddress getLocalHost( ) throws UnknownHostException - returns an
object of InetAddress class which contains information about local host
static InetAddress getByName(String hostname ) throws
UnknownHostException - returns an object of InetAddress class for a hostname
passed to it
static InetAddress[ ] getAllByName(String hostname ) throws
UnknownHostException - returns an array of all the objects of InetAddress
class which has a particular hostname
static InetAddress getByAddress( ) throws UnknownHostException - this
method takes an IP address and returns an object of InetAddress class for it
32. InetAddress class
All these methods throws UnknownHostException if they are unable to find the given
hostname
import java.io.*;
import java.net.*;
class InetAddressExample
{
public static void main(String args[]) throws
UnknownHostException
{
InetAddress obj1 = InetAddress.getLocalHost();
System.out.println(obj1);
System.out.println("------------------------------------------");
InetAddress obj2 =
InetAddress.getByName("www.gpgadchiroli.ac.in");
System.out.println(obj2);
System.out.println("------------------------------------------");
InetAddress obj3[] =
InetAddress.getAllByName("www.google.com");
for(int i=0;i<obj3.length;i++)
{
System.out.println(obj3[i]);
}
}
}
Program of InetAddress class :
34. Instance Methods of InetAddress class
Instance methods are those methods which require that object of its class must be
created before these methods are called
Some functions (instance methods) of InetAddress class are as follow
boolean equals(Object other) - returns true if the current object has same IP
address as other object passes as parameter
byte[ ] getAddress( ) - returns an array of data type byte shows Internet
address in network byte order
String getHostAddress( ) - Returns the host address in InetAddress object in
string format
35. Instance Methods of InetAddress class
Some functions (instance methods) of InetAddress class are as follow
boolean isMulticastAddress( ) - If the Internet address is multicast then it
returns true otherwise false
String toString( ) - It provides list of host name and IP address in string format
36. A socket is one endpoint of a two-way communication link between two programs
running on the network
TCP/IP Client Sockets
A socket has a port number linked with it
client
program
Server
program port (socket)
port (socket)
network
Server machine
Client machine
37. TCP/IP sockets provides reliable, bidirectional, persistent, point-to-point stream based
connections between hosts
TCP/IP Client Sockets
A socket connects java's I/O system to other program running on local machine or
network machine on the internet
There are two types of TCP sockets as follow :-
server socket
( ServerSocket class)
client socket
( Socket class )
38. ServerSocket class is like a 'listener' - that waits for client to get connected
TCP/IP Client Sockets
Socket class is used to connect to server sockets and start exchanging protocol
information
Socket(String hostName, int port) - this constructor creates a socket connecting
local host with given host named and port number
This constructor can throw UnknownHostException or IOException
Socket(InetAddress ipAddress, int port) - this constructor creates socket from
already existing InetAddess class object and port number
This constructor can throw IOException
39. We can get information like port number, IP address etc of a socket by using
following functions
TCP/IP Client Sockets
InetAddress getInetAddress( ) - returns InetAddress of a socket
int getPort( ) - returns remote port to which this Socket class object was connected
int getLocalPort( ) - returns local port to which this Socket class object was
connected
InputStream getInputStream( ) - returns InputStream class object linked with the
calling(invoking) socket
40. OutputStream getOutputStream( ) - returns the OutputStream class object linked
with the calling(invoking) socket
TCP/IP Client Sockets
getChannel( ) - this method returns the channel connected to Socket object
41. Uniform Resource Locator (URL)
Modern internet today does not use older protocols like - whois, finger, FTP
Today's internet is called as WWW (World Wide Web)
It is loose collection of higher-level protocols and file formats, all included in a web
browser
We can locate all resources on the web using concept called as 'Uniform Resource
Locator(URL)
URL uniquely identifies or address information on the internet
Web = All resources identified by URLs + HTML
42. How URL works ?
A Uniform Resource Locator (URL) is divided into four parts
Consider an example of URL - 'http://www.gpgadchiroli.ac.in/timetable.pdf' or
'http://www.gpgadchiroli.ac.in:80/timetable.pdf'
The first part of URL is a protocol used (http, gopher,ftp etc) , which is separated
from the remaining URL by colon(:) symbol - in the above example protocol used is
http
The second part of URL is a host name or IP address of a host, separated by double
splashes (//) from left and single slash or colon(:) symbol from right - in the above
example the host name is www.gpgadchiroli.ac.in
43. How URL works ?
The third part of URL is a port number, which is optional parameter
In the URL the port number is seperated from host name by colon(:) symbol from
left and single slash(/) from right side - in the above example the port number is 80
which is default port number of HTTP protocol
The fourth part of URL is a actual path of file, which we want
Most HTTP servers will join the file name with the URL - in the above example the
file we want is timetable.pdf or www.gpgadchiroli.ac.in/timetable.pdf
44. URL class in java
Java has a class called URL which creates and break up urls
URL class has many constructors which are as follow :
URL(String urlSpecifier) - this constructor creates a url in string format and
same url can also be seen in web browser
URL(String protocolName, String hostName, int port, String path) - this
constructor breaks down url into four parts i.e protocol name, host name, port
number and path of file
URL(String protocolName, String hostName, String path) - this constructor breaks
down url into three parts i.e protocol name, host name, and path of file
45. URL class in java
URL(URL urlObj, String urlSpecifier) - this constructor creates URL from already
created URL object.
Every constructor of URL class throws MalformedURLException
MalformedURLException is thrown when we create a wrong url or url cannot be
found on the net
46. Program of URL class
import java.io.*;
import java.net.*;
class URLExample
{
public static void main(String args[]) throws MalformedURLException
{
URL obj = new URL("https://gpgadchiroli.ac.in/gpgadchiroli_new/academics/institute-time-table/");
System.out.println("Protocol: "+obj.getProtocol());
System.out.println("Port: "+obj.getPort());
System.out.println("Host: "+obj.getHost());
System.out.println("File: "+obj.getFile());
System.out.println("Ext: "+obj.toExternalForm());
}
}
48. URLConnection class
URLConnection class is used for getting information about any remote resource
To access the information about URL, we first need to create and object of
URLConnection class using openConnection( ) function
The syntax of openConnection( ) function is as below :
URLConnection openConnection( ) - returns an URLConnection object associated
with calling URL object
This function may throw IOException
49. URLConnection class
When we connect to a remote server we can check the properties of remote object
using URLConnection class, before transporting that object to our local machine
We can get the following information about the remote object :
Date
Content-Type
Last-Modified
Content-Length, etc
URL and URLConnection classes are only good for simple programs that connects to
HTTP servers for getting the content
50. Program of URLConnection class
import java.io.*;
import java.net.*;
import java.util.Date;
class URLConnectionExample
{
public static void main(String args[]) throws Exception
{
URL obj = new URL("https://www.aicte-india.org/schemes");
URLConnection con = obj.openConnection();
long d = con.getDate();
if(d==0)
{
System.out.println("Date not available");
}
else
{
System.out.println("Date: "+new Date(d));
}
System.out.println("Content-Type: "+con.getContentType());
d = con.getLastModified();
if(d==0)
{
System.out.println("Last modified information not available");
}
else
{
System.out.println("Last Modified: "+new Date(d));
}
int len = con.getContentLength();
if(len==-1)
{
System.out.println("Content length not available");
}
else
{
System.out.println("Content-Length(bytes): "+len);
}
}
}
52. TCP/IP Server Sockets
ServerSocket class is used for creating servers
These servers listens (waits) for local clients or remote clients to connect to the
servers on particular port number
When we create ServerSocket, it will register itself with the operating system
It will tell the operating system that it is interested in connection to the client
Following are the constructors of ServerSocket class :
maxQueue - the total number of client connection that can remain pending before
server rejects any new connections
The default value of maxQueue is 50
53. TCP/IP Server Sockets
ServerSocket(int port, int maxQueue) - creates server socket on given port number
with given maxQueue value
ServerSocket(int port) - creates server socket on given port number with deafult
queue length of 50
ServerSocket(int port, int maxQueue, InetAddress localAddress) - creates server
socket on given port number with given maxQueue value and the IP address to
which the socket binds given by localAddress
accept( ) - this is a blocking function of ServerSocket class, used to wait for
communication with client and then return an object of Socket class which is used
for communication with client
54. Datagrams
Datagrams are packets of information passed between machines
When datagrams are send to the receiver there is no guarantee that the receive it
or not
Even when the receiver receives datagrams there is no guarantee that it correct or
damaged
Java implements datagram by using UDP protocol
It uses two classes for this - DatagramPacket class which is contains data and
DatagramSocket class which describes process for sending and receiving datagrams
55. DatagramPacket Class
Some of the constructors of DatagramPacket class are as follow :
DatagramPacket(byte data[ ], int size)
DatagramPacket(byte data[ ], int offset, int size)
DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
Where byte data[ ] = It is a buffer where received data will be stored
int size = size of the packet
int offset = It is offset in the buffer where data will be stored
InetAddress ipAddress = It is address of the target (destination) where
data packet will be sent by DatagramSocket class
56. DatagramPacket Class
int port = It is port number of the target where data packet will be
sent by DatagramSocket class
Some functions of DatagramPacket class are as follow :
InetAddress getAddress( ) - returns the destination InetAddress, where packet will
be sent
int getPort( ) - returns the port number
byte[ ] getData( ) - returns byte array of data present in the datagram, it is used to
get the data from the datagram after it is received at destination
int getLength( ) - returns length of valid byte array data in the datagram which is
returned by getData( ) function, it is equal to length of whole byte array
57. Inet4Address Class and Inet6Address Class
Inet4Address and Inet6Address classes are subclasses (child) classes of InetAddress
class
Inet4Address class represent IPv4 addresses
Inet6Address class represent IPv6 addresses
InetAddress class object can refer to both Inet4Address and Inet6Address class
We can simply use InetAddress class to work with both IPv4 and IPv6 addresses
58. URI Class
URI class contains Uniform Resource Identifiers which are used for identifying the
resources
URIs are simlilar to URLs
URLs are subset of URIs
A URI shows standard way to identify a resource
Whereas a URL also describes how to access (get) that resource
59. Simple Client-Server Program
Server program :-
import java.net.*;
import java.io.*;
class ServerExample
{
public static void main(String args[])throws Exception
{
ServerSocket server_socket = new ServerSocket(3428);
Socket s = server_socket.accept();
DataInputStream data_in = new DataInputStream(s.getInputStream());
DataOutputStream data_out = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
System.out.println("Server is running...........");
while(!str.equals("stop"))
{
str=data_in.readUTF();
System.out.println("client message is : "+str);
str2=br.readLine();
data_out.writeUTF(str2);
data_out.flush();
}
data_in.close();
s.close();
server_socket.close();
}
}
60. Simple Client-Server Program
Client program :-
import java.net.*;
import java.io.*;
class ClientExample
{
public static void main(String args[])throws Exception
{
Socket s = new Socket("localhost",3428);
DataInputStream data_in = new DataInputStream(s.getInputStream());
DataOutputStream data_out = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
System.out.println("Client is running.........");
while(!str.equals("stop"))
{
str = br.readLine();
data_out.writeUTF(str);
data_out.flush();
str2=data_in.readUTF();
System.out.println("Server message is : "+str2);
}
data_out.close();
s.close();
}
}