Chapter 20
Networking
9-Feb-24
In this chapter
Monica Patel
2
Introduction
◼ Java Networking is a concept of connecting two or more
Monica Patel
computing devices together so that we can share
resources.
◼ The java.net package supports two protocols,
◼ TCP: Transmission Control Protocol provides reliable
communication between the sender and receiver. TCP is
used along with the Internet Protocol referred as
TCP/IP.
◼ UDP: User Datagram Protocol provides a connection-
less protocol service by allowing packet of data to be
transferred along two or more nodes
3
Networking Terminology
◼ IP Address
◼ The IP address is a 32-bit number and is expressed as a group
Monica Patel
of four numbers separated by a dot.
◼ IP address is a unique number assigned to a node of a network
e.g. 192.168.0.1 . It is composed of octets that range from 0 to
255.
◼ It is a logical address that can be changed.
◼ Protocol
◼ A protocol is a set of rules basically that is followed for
communication. For example: TCP, FTP, Telnet, SMTP etc.
◼ Port Number
◼ The port number is used to uniquely identify different
applications. It acts as a communication endpoint between
applications. 4
Networking Terminology
◼ Connection-oriented and connection-less protocol
Monica Patel
◼ In connection-oriented protocol, acknowledgement is sent by
the receiver. So it is reliable but slow. The example of
connection-oriented protocol is TCP.
◼ But, in connection-less protocol, acknowledgement is not sent
by the receiver. So it is not reliable but fast. The example of
connection-less protocol is UDP.
◼ Socket
◼ A socket is an endpoint between two way communications.
5
InetAddress
◼ Inet Address encapsulates both numerical IP address
and the domain name for that address.
Monica Patel
◼ Inet address can handle both IPv4 and Ipv6 addresses.
◼ Inet Address class has no visible constructor.
◼ To create an inetAddress object, you have to
use Factory methods.
◼ Three commonly used Inet Address factory methods
are.
◼ static InetAddress getLocalHost()
◼ static InetAddress getByName (String hostname)
◼ static InetAddress[ ] getAllByName (String hostname)
6
InetAddress
◼ static InetAddress getLocalHost()
Monica Patel
◼ Returns the IP address of the local host; throws
UnknownHostException
◼ static InetAddress getByName(String host)
◼ Returns the IP address for the given host; the host name can
either be a machine name like “ruraluniv.org” or a string
representing its IP address “205.31.45.101”. Throws
UnknownHostException
◼ static InetAddress[] getAllByName(String host)
◼ Returns an array of all the IP addresses for the given host; the
host name can either be a machine name or its IP address.
Throws UnknownHostException
7
InetAddress
◼ Remembering the IP address as a sequence of four numbers is
difficult.
Monica Patel
◼ Therefore, every IP address is associated with a string called
domain name.
◼ For example, the IP address 192.18.97.71 is associated with
www.java.sun.com and IP address 66.33.109.23 is associated
with the name www.ruraluniv.org.
◼ A server keeps the database of IP addresses and the associated
domain names.
◼ Such servers are called Domain Name System(DNS).
8
Program
import java.net.*;
class Demo
Monica Patel
{
public static void main(String[] args) throws UnknownHostException
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address = InetAddress.getByName("www.studytonight.com");
System.out.println(address);
InetAddress sw[] = InetAddress.getAllByName("www.google.com");
for(int i=0; i< sw.length; i++)
{
System.out.println(sw[i]);
}
}
} 9
Output
Welcome-PC/59.161.87.227
Monica Patel
www.studytonight.com/208.91.198.55
www.google.com/74.125.236.115
www.google.com/74.125.236.116
www.google.com/74.125.236.112
www.google.com/74.125.236.113
www.google.com/74.125.236.114
www.google.com/2404:6800:4009:802:0:0:0:1014
10
Socket Programming
◼ To establish a connection between one host and another in a
network, the socket mechanism is used.
Monica Patel
◼ A socket is used to connect the Java’s I/O to other programs in
the same machine or to another host on the network.
◼ Once a connection is established, higher-level protocols are used
to do the required services.
◼ Each protocol is realized through a concept called port. A port is
identified by a number that will automatically follow a
predefined protocol.
◼ For example, port no. 21 is for FTP(File Transfer Protocol), 23 is
for Telnet, 80 is for HTTP and so on.
11
Socket Programming
◼ Sockets provide the communication mechanism
between two computers using TCP.
Monica Patel
◼ Java Socket programming can be connection-oriented or
connection-less.
◼ Socket and ServerSocket classes are used for
connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
◼ The client in socket programming must know two
information:
1. IP Address of Server, and
2. Port number.
12
Monica Patel
13
Steps to establishing a TCP connection between two
computing devices using Socket Programming
◼ Step 1 – The server instantiates a ServerSocket object, indicating at
which port number communication will occur.
Monica Patel
◼ Step 2 – The server requests the accept() method of the
ServerSocket class. This program pauses until a client connects to
the server on the given port.
◼ Step 3 – After the server is idling, a client instantiates an object of
Socket class, defining the server name and the port number to
connect to.
◼ Step 4 – After the above step, the constructor of the Socket class
strives to connect the client to the designated server and the port
number. If communication is authenticated, the client forthwith has
a Socket object proficient in interacting with the server.
◼ Step 5 – On the server-side, the accept() method returns a reference
to a new socket on the server connected to the client’s socket.
14
ServerSocket (TCP/IP)
◼ The ServerSocket class can be used to create a server
socket.
Monica Patel
◼ A server socket keeps waiting for request calls from the
network.
◼ When a request is received, it does some operation
appropriate to the request and returns a reply to the
caller.
◼ The constructor for ServerSocket class throws an
exception if it can’t listen on the specified port.
◼ For example – it will throw an exception if the port is
already being used.
15
Constructors
◼ ServerSocket(int port)
Monica Patel
◼ Creates a server socket on a specified port; a port of 0 creates
a socket on any free port. The maximum queue length for
incoming connection is set to 50.
◼ ServerSocket(int port, int q)
◼ Creates a server socket on the specified port; the maximum
queue length is set to q.
◼ ServerSocket(int port, int q, InetAddress address)
◼ Creates a server socket on the specified port with a maximum
queue length of q; in a multi-homed host, address specifies the
IP address to which the socket binds.
16
Methods of ServerSocket Class:
◼ InetAddress getInetAddress()
◼ Returns the local address of this server socket
Monica Patel
◼ int getLocalPort()
◼ Returns the port number on which this socket is listening
◼ Socket accept()
◼ Listens for a connection to be made to this socket and accepts
it; a new socket is created. It throws an IOException.
◼ void close()
◼ Closes this socket; throws IOException if an I/O error occurs
when closing the socket
17
Methods
◼ void setSoTimeout(int timeout)
Monica Patel
◼ Enables/disables SO_TIMEOUT with the specified timeout in
milliseconds; with a non-zero timeout, a call to accept() for
this ServerSocket will block for only this much amount of
time. After the expiry of the timeout, InterruptedIOException
is thrown out. This method will also throw SocketException.
◼ int getSoTimeout()
◼ Returns the SO_TIMEOUT; a 0 value implies that the option
is disabled.
18
Client Socket(TCP/IP)
◼ The client socket is implemented in the class Socket.
Monica Patel
◼ A socket is an end point for communication between
two host machines.
◼ A client socket establishes a connection with the server
socket.
◼ The connection is a reliable, connection-oriented
TCP/IP connection.
◼ Once a connection is established, methods defined in
SocketImpl class are used to carry out the desired task.
19
Constructors
◼ Socket(String host, int port)
Monica Patel
◼ Creates a stream socket and connects it to the specified port
number on the specified host; throws an
UnknownHostException and IOException
◼ Socket(InetAddress address, int port)
◼ Creates a stream socket and connects it to the specified port
number at the specified IP address; throws an IOException
◼ Socket(InetAddress address, int port, InetAddress
localadrs, int localport)
◼ Creates a socket and connects it to the specified remote
address and remote port; the socket binds to the local address
and the specified local port. Throws an IOException
20
Methods
◼ InetAddress getInetAddress()
Returns the remote IP address to which this socket is
Monica Patel
connected
◼ InetAddress getLocalAddress()
◼ Returns the local address to which the socket is connected
◼ int getPort()
◼ Returns the remote port number to which this socket is
connected
◼ int getLocalPort()
◼ Returns the local port number to which this socket is
connected
21
Methods
◼ InputSream getInputStream()
Monica Patel
◼ Returns an input stream for reading bytes from this socket;
throws an IOException
◼ OutputStream getOutputStream()
◼ Returns an output stream for writing bytes to this socket;
throws an IOException
◼ void close()
◼ Closes this socket; throws an IOException.
22
Example of Java Socket
Programming
◼ Creating Server:
◼ To create the server application, we need to create the instance of
Monica Patel
ServerSocket class. Here, we are using 6666 port number for the
communication between the client and server. You may also choose
any other port number. The accept() method waits for the client. If
clients connects with the given port number, it returns an instance of
Socket.
◼ ServerSocket ss=new ServerSocket(6666);
◼ Socket s=ss.accept();//establishes connection and waits for the client
◼ Creating Client:
◼ To create the client application, we need to create the instance of
Socket class. Here, we need to pass the IP address or hostname of
the Server and a port number. Here, we are using "localhost"
because our server is running on same system.
◼ Socket s=new Socket("localhost",6666); 23
File: MyServer.java
import java.io.*;
import java.net.*;
Monica Patel
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
24
File: MyClient.java
import java.io.*;
import java.net.*;
Monica Patel
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
25
Contd….
◼ To execute this program open two command prompts
Monica Patel
and execute each program at each command prompt as
displayed in the below figure.
◼ After running the client application, a message will be
displayed on the server console.
26
Monica Patel
27
DatagramSocket and DatagramPacket
◼ Datagrams are fire-and-forget type of message packets.
Monica Patel
◼ Java DatagramSocket and DatagramPacket classes are
used for connection-less socket programming using the
UDP instead of TCP.
◼ The preparation of datagram packets are handled in
DatagramPacket class and the delivery mechanism is
handled by DatagramSocket class.
28
Datagram
◼ Datagrams are collection of information sent from one
Monica Patel
device to another device via the established network.
◼ When the datagram is sent to the targeted device, there
is no assurance that it will reach to the target device
safely and completely.
◼ It may get damaged or lost in between.
◼ Likewise, the receiving device also never know if the
datagram received is damaged or not.
◼ The UDP protocol is used to implement the datagrams
in Java.
29
1. DatagramPacket Class
◼ A message to be transmitted is broken into small
Monica Patel
message packets of a certain length.
◼ The IP address of the destination is also packed into it.
◼ The preparation of datagram packets are handled in the
Datagrampacket class.
◼ DatagramPacket is a message that can be sent or
received. It is a data container.
◼ If you send multiple packet, it may arrive in any order.
Additionally, packet delivery is not guaranteed.
30
Constructors of DatagramPacket class
◼ DatagramPacket(byte[] buf, int offset, int length)
◼ Constructs a datagram packet for receiving packets of byte length
Monica Patel
length, into the buffer buf starting at offeset in the array
◼ DatagramPacket(byte[] buf, int length)
◼ Constructs a datagram packet for receiving packets of byte length of
length
◼ DatagramPacket(byte[] buff, int offset, int length, InetAddress
address, int port)
◼ Constructs a datagram packet for sending packets of length, length with
offset at offset, to the specified port on the specified host of address
address
◼ DatagramPacket(byte[] buff, int length, InetAddress address, int
port)
◼ Constructs a datagram packet for sending packets of length, length to
the specified port number on the specified host of address, address 31
Methods of DatagramPacket
◼ InetAddress getAddress()
Returns the IP address of the machine to which this datagram
Monica Patel
is being sent or from which the datagram is received
◼ int getPort()
◼ Returns the port number on the remote host to which this
datagram is being sent or from which the datagram is received
◼ byte[] getData()
◼ Returns the data bytes received or the data bytes to be sent
◼ int getLength()
◼ Returns the length of the data to be sent or the length of the
data received
32
Methods of DatagramPacket
◼ void setAddress(InetAddress address)
Monica Patel
◼ Sets the IP address for this packet
◼ void setPort(int port)
◼ Sets the port number for this packet
◼ void setData(byte[] buf)
◼ Sets the data buffer for this packet
◼ void setLength(int length)
◼ Sets the length in bytes for this packet
33
2. DatagramSocket class
◼ DatagramSocket class represents a connection-less
Monica Patel
socket for sending and receiving datagram packets.
◼ It is a mechanism used for transmitting datagram
packets over network.
◼ A datagram is basically an information but there is no
guarantee of its content, arrival or arrival time.
◼ The datagram packets may follow different routes to
reach the destination.
◼ Multiple packets sent from a source may reach the
destination in any order.
34
Constructors of DatagramSocket
class
◼ DatagramSocket() throws SocketException: it creates
Monica Patel
a datagram socket and binds it with the available Port
Number on the localhost machine.
◼ DatagramSocket(int port) throws SocketException:
it creates a datagram socket and binds it with the given
Port Number.
◼ DatagramSocket(int port, InetAddress address)
throws SocketException: it creates a datagram socket
and binds it with the specified port number and host
address.
35
Methods of DatagramSocket
◼ void connect(InetAddress adrs, int port)
◼ Connects the socket to a remote address and remote port;
Monica Patel
when a socket is connected to a remote address, packets may
only be sent to or received from that address.
◼ void disconnect()
◼ Disconnects the socket
◼ InetAddress getInetAddress()
◼ Returns the address to which this socket is connected
◼ int getPort()
◼ Returns the port number to which this socket is connected
36
Methods of DatagramSocket
◼ void send(DatagramPacket p)
Monica Patel
◼ Sends a datagram packet from this socket; throws an IOException
◼ void receive(DatagramPacket p)
◼ Receives a datagram packet from this socket; when this method returns,
the DatagramPacket’s buffer is filled with the data received. Throws an
IOException
◼ InetAddress getLocalAddress()
◼ Returns the local address to which the socket is bound
◼ int getLocalPort()
◼ Returns the port number on the local host to which this socket is bound
◼ void close()
◼ Closes this socket
37
Example of Sending DatagramPacket by
DatagramSocket
//DSender.java
import java.net.*;
Monica Patel
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();
}
}
38
Example of Receiving DatagramPacket
by DatagramSocket
//DReceiver.java
import java.net.*;
Monica Patel
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();
}
}
39
URL
◼ The Java URL class represents an URL.
◼ URL is an acronym for Uniform Resource Locator. It points to a
Monica Patel
resource on the World Wide Web.
◼ URL unifies many higher-level protocols and file formats into a
single form called web or World Wide Web.
◼ Such a web is uniquely identified by an address specified by
URL. All web browsers use URL to identify resources in the
internet.
◼ For example:
◼ https://www.javatpoint.com/java-tutorial
40
URL
◼ The URL format consists of four parts.
Monica Patel
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/sonoojaiswal/ , 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.
41
Constructors
◼ URL(String spec)
Monica Patel
◼ Creates a URL object from the string specification spec;
throws MalformedURLException
◼ URL(URL context, String spec)
◼ Creates a URL by parsing the specification spec within a
specified context; if the context is not null and the spec
argument is a partial URL specification, any of the string’s
missing components are inherited from the context argument.
Throws MalformedURLException
42
Methods
◼ int getPort()
Returns port number of this URL; returns -1 if the port is not
Monica Patel
set
◼ String getProtocol()
◼ Returns the protocol name of this URL
◼ String getHost()
◼ Returns the host name of this URL, if applicable; for “file”
protocol, this is an empty string.
◼ String getFile()
◼ Returns the file name of this URL
43
Methods
◼ URLConnection openConnection()
Monica Patel
◼ Returns a URLConnection object that represents a connection
to the remote object referred to by the URL; throws an
IOException
◼ final InputStream openStream()
◼ Opens a connection to this URL and returns an InputStream
for reading from that connection; this method represents a
short-hand method for openConnection.getInputstream().
Throws an IOException
◼ final Object getContent()
◼ Returns the contents of this URL; this is equivalent to
openConnection.getContent(). Throws an IOException
44
//URLDemo.java
import java.net.*;
Monica Patel
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
45
Output
◼ Protocol: http
Monica Patel
◼ Host Name: www.javatpoint.com
◼ Port Number: -1
◼ File Name: /java-tutorial
46