UNIT – IV
NETWORKING BASICS
Unit Outcomes (UOs): -
4a. Use of Inet Address class .
4b.Use of URLConnection Class to read and write data.
4c.Develop Client/Server Communication program through TCP/IP Sockets.
4d. Develop Client/Server Communication program using datagram
protocol.
Total Marks=10
CH-3 NETWORKING BASICS
Java a good language for networking are the classes defined in the java.net package. These networking classes
encapsulate the “socket”
Networking Basics
Ken Thompson and Dennis Ritchie developed UNIX in concert with the C language at Bell Telephone Laboratories.
Berkeley’s implementation of TCP/IP remains the primary standard for communications within the Internet.
Socket Overview
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 in” to the socket and
communicate.
Socket Overview
• Socket is the most commonly used term in network programming. Socket
provides the way by which the computers can communicate using connection oriented or
connection less communication.
• Definition of socket : A socket is basically an endpoint of a two-way
communication link between two programs running on the network. It is OS-controlled
interface into which the applications can send or receive messages to and fro from
another application.
The java.net.Socket class represents the socket.
Two key classes are used to create the socket.
i) ServerSocket
ii) Socket
• A server program creates a specific type of socket that is used to listen for client requests (server
socket), In the case of a connection request, the program creates a new socket through which it will exchange
data with the client using input and output streams
The ServerSocket can be created with the help of port number. For example
∙
ServerSocket server_socket=new Socket(1234);
∙ The Socket object can be created with the help of hostname and port number. The general syntax of socket
instantiation is
Socket client= new Socket(serverName, portNumber);
Example:
Socket client_socket=new Socket(“myserver”,1234);
The ServerSocket listens the client using the accept
method. For example
Socket Listen_socket=server_socket.accept();
There are two types of sockets :–
i) TCP Sockets : These are denoted by streams.
ii) UDP Sockets : These are denoted by datagrams.
Client Server
In client server communication, there are 3 components.
1) Client PC or web client
2) An application server or web server
3) A database server
.
Working
Step 1 : The client PC or web client submits the request for desired web page to the web server
Step 2 : The work of server is distributed among application server and database servers. Application server possess
the required communication functions
Step 3 : The data required by this business logic is present on database server. The required data is returned to
application servers.
Step 4 : The web server or application server prepares the response page and sends it to the web client.
Reserved Sockets
∙ In network programming, the port is a medium through which one application establishes connection with
other application by binding socket using port number.
∙ With the help of port number and some additional information data is transferred from client to server or
from server to client.
∙ There are some ports which are reserved for specific service. These ports are called as reserved ports.
• Various port numbers specifying their services are given in the following table
Port number Service
21 FTP
23 Telnet
25 SMTP
80 HTTP
110 POP3
• User level processes or services generally use port numbers >=1024.
Proxy Servers
What is proxy server ? : A proxy server is a server that sits between a client application and a real server. It intercepts all
requests to the real server to see if it can fulfill the requests itself. If not, it forwards the request to the real server.
What is the purpose of having proxy server ?
Role of port in socket programming
∙ A server runs on specific computer and has a socket that is bound to specific port. Here the port number must be other than
the reserved port numbers. Usually it is >=1024. For example - If I use port number 1122 for client server communication
then it is a valid port number. But if I make use of port
1)
It improves the performance by caching the information.
To understand the concept of caching consider a scenario -
Suppose there are two users - user X and user Y access the World Wide Web through a proxy server. First user X
requests a certain web page, which we'll call page 1. Sometime later, user Y requests the same page. Instead of
forwarding the request to the web server where page 1 resides, which can be a time-consuming operation, the
proxy server simply returns the page 1 that it already fetched for user X. Since the proxy server is often on the same
network as the user, this is a much faster operation.
It provides security and privacy. Because it prevents clients to access sensitive information directly from the server.
Working of proxy server
Internet Addressing
• Every computer on internet has address. This is called IP address or Internet Protocol Address.
• This is unique 32 bit logical address divided into two main parts - Network Number and Host number.
InetAddress
• The InetAddress class from java.net package represents the IP addresses.
• It works with either host name or numerical IP address of corresponding host.
• InetAddress class offers many useful methods for handling IP addresses and host names.
Factory Methods
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. Three commonly used InetAddress factory methods are shown
here.
static InetAddress getLocalHost( )throws UnknownHostException
static InetAddress getByName(String hostName) throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that represents the local host.
The getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to resolve
the host name, they throw an UnknownHostException.
This program make use of the method getLocalHost() method for finding the IPaddress of local host
machine.
import java.net.*;
class InetAdd1
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress local_add=InetAddress.getLocalHost(); System.out.println(“Local Host is: ”+local_add);
}
}
D:\test>javac InetAdd1.java D:\test>java InetAdd1
Output
Local Host is: aap/192.168.0.166
the above program you get the IP address of the local machine on which you are running your program along with
the host name
3) One more important thing about the above Java program and that is definition
of main function. It should be
public static void main(String args[]) throws UnknownHostException
That means, it is a must to throw an exception for unknown host in order to handle
unknown host situation. Hence precisely UnknownHostException should be thrown.
This program shows the use of the method getByNamefor getting the IP address for the corresponding host
name
import java.net.*;
class InetAdd2
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress addr =InetAddress.getLocalHost();
System.out.println(addr);
Address=InetAddress.getByName(“vtubooks.com”);
System.out.println(addr);
}
}
Output
D:\test>java InetAdd2 aap/192.168.0.166
vtubooks.com/202.137.237.142
While running the above program if your computer is not connected to internet then it will generate following
output [In fact here is the real use of throwing an exception].
The factory method getAllByName().
Sol. : This function is used to find the several machines that are associated with single several IP addresses. There are
some cases in which single domain name may be associated with several machines. for getting all the IP addresses
related to the same host name.
import java.net.*;
class InetAdd3
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress[] addr=InetAddress.getAllByName(“www.microsoft.com”);
for(int i=0;i<addr.length;i++) System.out.println(addr[i]);
}
}
D:\test>javac InetAdd3.java
D:\test>java InetAdd3
OUTPUT:
www.microsoft.com/207.46.19.254
www.microsoft.com/207.46.192.254
www.microsoft.com/207.46.193.254
www.microsoft.com/207.46.19.190
Instance Methods
An instance method in Java is basically a method of the class. In other words, a non-static method which is
declared inside a class is an instance method. This kind of method requires an object of its class to created
before it can be called. To invoke an instance method, we have to create the object of the class. InetAddress
Class Methods
This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would
need while doing socket programming −
Method & Description
1static InetAddress getByAddress(byte[] addr)-🡪 Returns an InetAddress object given the raw IP address.
2 static InetAddress getByAddress(String host, byte[] addr)Creates an InetAddress based on the provided host
name and IP address.
3. static InetAddress getByName(String host)🡪 Determines the IP address of a host, given the host's name.
4String getHostAddress()-🡪 Returns the IP address string in textual presentation.
5.String getHostName()🡪 Gets the host name for this IP address.
6.static InetAddress InetAddress getLocalHost()🡪 Returns the local host.
7.String toString()🡪 Converts this IP address to a String.
TCP, IP and UDP
TCP:
∙ Transmission Control Protocol(TCP) is a connection-oriented, reliable protocol which supports the transfer of data in
continuous streams.
∙ This is called connection-oriented protocol because control information is sent before transmitting any data. This
process is sometimes called as handshaking.
∙ This is a reliable protocol because any data which when gets lost or corrupted, the TCP has a provision to retransmit it.
∙ The addressing scheme used in TCP is by means of ports. During this communication, the server waits for the client to
get connected to a specific port for establishing communication. This type of communication is called as socket
programming.
IP
∙ Internet protocol is a major protocol in the TCP/IP suit.
∙ It is a connectionless, unreliable protocol which supports the transfer of data in the form of packets.
∙ This is called connectionless protocol because it does not exchange any control information before transmitting any
data. The data is just sent to the destination with a hope that it will reach at appropriate place.
∙ IP is known as an unreliable protocol because it does not have the provision of retransmitting the lost packets or detect
the corrupted data.
∙ The addressing scheme used in IP is by means of IP addresses. An IP address is a 32-bit unique number. IP addresses
are generally written as four numbers, between 0 and 255, separated by period. Using the IP address defined in IP
packet header,the IP packets can be routed to its destination
UDP
• The User Datagram Protocol (UDP) is a low- overhead protocol which can be used as an alternative to TCP
protocol.
• The UDP is a connectionless, unreliable protocol in which the data is passed in the form of datagrams.
• This is called connectionless protocol because it does not exchange any control information before
transmitting any data. The data is just sent to the destination with a hope that it will reach at appropriate place.
• UDP is known as an unreliable protocol because it does not have the provision of retransmitting the lost
datagram or detect the corrupted data.
The addressing scheme used UDP is by means of ports. On separate ports the communication can be established
concurrently by the system. UDP ports are distinct from the TCP port
TRANSMISSION CONTROL PROTOCOL (TCP) USER DATAGRAM PROTOCOL (UDP)
TCP is a connection-oriented protocol. Connection- UDP is the Datagram oriented protocol. This is because
orientation means that the communicating devices should there is no overhead for opening a connection, maintaining a
establish a connection before transmitting data and should connection, and terminating a connection. UDP is efficient
close the connection after transmitting the data. for broadcast and multicast type of network transmission.
TCP is reliable as it guarantees delivery of data to the The delivery of data to the destination cannot be guaranteed
destination router. in UDP.
TCP provides extensive error checking mechanisms. It is
UDP has only the basic error checking mechanism using
because it provides flow control and acknowledgment of
checksums.
data.
Sequencing of data is a feature of Transmission Control
There is no sequencing of data in UDP. If ordering is
Protocol (TCP). this means that packets arrive in-order at the
required, it has to be managed by the application layer.
receiver.
UDP is faster, simpler and more efficient than TCP.
TCP is comparatively slower than UDP
TCP/IP Client Sockets
• A socket is bound to a port number so that the TCP/UDP from transport layer can identify the
corresponding application at destination.
• TCP sockets are denoted by streams and server is a device which has resources and from which the services
can be obtained. For example : there are various types of servers such as web server which is for storing the web
pages, there are print servers for managing the printer services or there are database servers which store the
databases.
• Client is a device which wants to get service from particular server.
There are two constructors used to create client socket –
The java.net.Socket class represents the socket that both the client and the server use to communicate with
each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket
object from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server −
public Socket(String host, int port) throws UnknownHostException, IOException.
This method attempts to connect to the specified server at the specified port. If this constructor does not throw an
exception, the connection is successful and the client is connected to the server.
2 public Socket(InetAddress host, int port) throws IOException
This method is identical to the previous constructor, except that the host is denoted by an InetAddress object.
public InetAddress getInetAddress()
This method returns the address of the other computer that this socket is connected to.
3.public int getPort()
Returns the port the socket is bound to on the remote machine.
4.public int getLocalPort()
Returns the port the socket is bound to on the local machine
URL
• For identifying the documents on the internet the uniform or universal resource locator i.e. URL is used.
• There is variety of URL depending upon the type of resources.
protocol://username@hostname/path/filename
• The scheme specifies the communication protocol. Different schemes have different schemes have
different forms of addresses.
• Various schemes that are used are http, ftp, gopher, file, mailto, news and so on.
• The most commonly used protocol for web browser and web server communication is Hypertext Transfer
Protocol(HTTP). This protocol is based on request-response mechanism. This protocol handles the documents that
are created using eXtensible Hypertext Markup Language (XHTML)
file is another most commonly used scheme in URL. This protocol allows to reside the document in the client’s
machine from which the web browser is making out the demand.
∙ The hostname is the name of the server computer that stores the web documents.
∙ The default port number for the http protocol is 80.
∙ Any URL does not allow the spaces in it. But there are some special characters that can be present in the
URL. These characters are - ampersand & or percentage % .
TCP/IP Client Sockets
• A socket is bound to a port number so that the TCP/UDP from transport layer can identify the
corresponding application at destination.
• TCP sockets are denoted by streams and server is a device which has resources and from which
the services can be obtained. For example : there are various types of servers such as web server which is
for storing the web pages, there are print servers for managing the printer services or there are database
servers which store the databases.
• Client is a device which wants to get service from particular server.
There are two constructors used to create client socket :
1.public Socket(String host, int port) throws UnknownHostException, IOException.
This method attempts to connect to the specified server at the specified port. If this constructor does not
throw an exception, the connection is successful and the client is connected to the server.
2.public Socket(InetAddress host, int port) throws IOException
This method is identical to the previous constructor, except that the host is denoted by an InetAddress object.
URL
• For identifying the documents on the internet the uniform or universal resource locator i.e. URL is used.
• There is variety of URL depending upon the type of resources.
Format
• The general format of URL is -
protocol://username@hostname/path/filename
• The scheme specifies the communication protocol. Different schemes have different schemes have different
forms of addresses.
• Various schemes that are used are http, ftp and so on.
• The most commonly used protocol for web browser and web sThe URL Path
• The path to the web document is similar to the path to the particular file present in the folder. In this path
the directory names and files are separated by the separator characterserver communication is Hypertext Transfer
Protocol(HTTP). This protocol is based on request-response mechanism.
•
The URL Path:
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the
World Wide Web.
For example:
https://www.javatpoint.com/java-tutorial
URL in Java
A URL contains many information:
1.Protocol: In this case, http is the protocol.
2.Server name or IP Address: In this case, www.javatpoint.com is the server name.
3.Port Number: It is an optional attribute.
If we write http//ww.javatpoint.com:80// index.jsp , 80 is the port number.
If port number is not mentioned in the URL, it returns -1.
4.File Name or directory name: In this case, index.jsp is the file name.
The URL Class
• The Java’s URL class has various constructors. These constructors throw the exception
MalformedURLException.
• The syntax to specify the URL constructor is as follows: -
URL(String URLString);
URL(String protocolName, String hos, int port, String path)
URL(String protocolName, String host, String path)
Commonly used methods of Java URL class
The java.net.URL class provides many methods. The important methods of URL class are given below.
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
Write a Java program to obtain the name of the protocol, port number, host name and file name of the
URL.
Sol. :
import java.net.*;
class MyURLDemo
{
public static void main(String args[])throws MalformedURLException
{
URL obj=new URL("http://technicalpublications.org/index.php/");
System.out.println("Protocol: " + obj.getProtocol());
System.out.println("Port: " + obj.getPort());
System.out.println("Host: " + obj.getHost());
System.out.println("File: " + obj.getFile());
}
}
Output
Protocol: http Port: -1
Host: technicalpublications.org File: /index.php/
URLConnection
• The class URLConnection is used for accessing the attributes of remote resource. These attributes are
exposed by the HTTP protocol.
• Using the OpenConnection( ) method of URL class we can examine the contents. This method is used to
establish the connection with some specific web site. Hence to get the contents of the web page we used
following statement –
URLConnection handle_connection=handle.openConnection();
Here handle_connection is an object of class URLConnection. Thus the openConnection() method returns object
of URLConnection.
TCP/IP Server Sockets
• The ServerSocket class is used to create servers that listen to its clients.
• When ServerSocket is created, it will register itself with the system so that
clients can connect to it. This class throws exception IOException.
• Various ways by which ServerSocket can be created is as follows -
ServerSocket(int port)
ServerSocket(int port, int maxQueue)
ServerSocket(int port, int maxQueue, InetAddress localAddress)
• Using the accept() method, the server initiates the communication with the
client.
Datagrams
• A datagram is an independent, self-contained message sent over the network whose arrival, arrival time and
content are not guaranteed.
• It is a basic transfer unit associated with a packet-switched network. The applications that communicate via
datagrams send and receive completely independent packets of information.
• The java.net package contains three classes to help you write Java programs that use datagrams to send and
receive packets over the network : DatagramSocket, DatagramPacket, and MulticastSocket.
• An application can send and receive DatagramPackets through a DatagramSocket. In addition,
DatagramPackets can be broadcast to multiple recipients all listening to a MulticastSocket.
Datagram Packet
• The DatagramPacket is a message that can be sent or received.
• An application can send and receive DatagramPackets through a
DatagramSocket.
• If you send multiple packets then these packets may arrive in any order.
Moreover, the delivery of packets is also not guaranteed.
Constructors used for DatagramPacket:
• DatagramPacket(byte[] barr, int length) : It creates a datagram packet. This
constructor is used to receive the packets.
• DatagramPacket(byte[] barr, int length, InetAddress address, int port) : It creates
a datagram packet. This constructor is used to send the packets.
Methods
Here are some useful methods for UDP socket programming
Method Description
InetAddress getByName(String hostname) This method returns the IP address when the hostname is
given.
.
InetAddress getAddress() This method returns the IP address.
int getPort() It returns the port number.
Byte [ ]getData() It returns the data containing in the
datagram. This is stored in the
array of bytes.
int getLength() Returns the length of data
obtained by getData method.