0% found this document useful (0 votes)
13 views40 pages

2024_CN_Practicals_1_to_10

The document outlines lab experiments for a Computer Networks course at L E College, Morbi, for the academic year 2024-25. It includes practical exercises on network configuration, subnetting, FTP server setup, and Apache server installation on Ubuntu Linux. Each section provides detailed steps and configurations necessary for completing the tasks, including examples and testing procedures.

Uploaded by

pratham.prydan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views40 pages

2024_CN_Practicals_1_to_10

The document outlines lab experiments for a Computer Networks course at L E College, Morbi, for the academic year 2024-25. It includes practical exercises on network configuration, subnetting, FTP server setup, and Apache server installation on Ubuntu Linux. Each section provides detailed steps and configurations necessary for completing the tasks, including examples and testing procedures.

Uploaded by

pratham.prydan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

En:230313116010

IT Department
L E College, Morbi (Degree)
Academic Year: 2024-25
Lab Experiments
Course: Computer Networks (3150710)
No. Aim
1 To study basic network configuration of a PC.
2 (a) Define IP address. Give an example.
(b) Discuss how to identify class of an IP address.
(c) Discuss how classes differ in netid and hostid.
(d) Write network masks for class A, B and C.
(e) Explain allocation of block of addresses for each class using diagram (No
description required)
3 (a)Define subnetting.
(b)Perform subnetting as follows.
1. Consider a block of IP addresses whose one IP address is 132. 14. 23.
4. Divide this block into 8 subnets.
2. Consider a block of IP addresses whose one IP address is 10. 0. 0. 4.
Divide this block into 4 subnets.
3. Consider a block of IP addresses whose one IP address is 221. 182. 3.
4. Divide this block into 4 subnets.

For above 3 subnetting examples, answer the following questions also.


a.What is network address and broadcast address of the block without subnetting ?
b.How many hosts can be present in the block without subnetting.
c. What is network mask without subnetting ?
d.What is subnet address and broadcast address of each subnet?
e.How many hosts can be present in each subnet.

(c)An organization is granted the block 130.34.12.64/26. The organization needs 4


subnets. Perform subnetting. Answer following questions:

a.What is network address and broadcast address of the block without subnetting ?
b.How many hosts can be present in the block without subnetting.
c. What is network mask without subnetting ?
d.What is subnet address and broadcast address of each subnet?
e.How many hosts can be present in each subnet
En:230313116010
Practical 4

Aim: Perform subnetting using cisco packet tracer. Demonstrate for both
cases- classful and classless addressing.

CLASSFUL
1. Place 5 pcs on the workspace and connect them together with the help of a switch
2. Now 4 of the following pcs belong to the same subnet and the other one belongs to a
different subnet.
3. Dividing network 142.16.0.1 into 4 subnets

4. Pc0: IP: 142.16.2.1


Pc1: IP: 142.16.3.1
Pc2: IP: 142.16.35.1
Pc3: IP: 142.16.66.1
Pc4: IP: 142.16.129.1
Pc5: IP: 142.16.130.1
Pc6: IP: 142.16.193.1
Pc7: IP: 142.16.194.1
En:230313116010
5. Ping a pc in the same subnet.

6. Ping a pc in different subnet.

So the pcs in one subnet can interact whereas the ones lying in different subnets
cannot.
En:230313116010

CLASSLESS

1. Given IP Address – 159.16.0.0/25


Pc01:159.16.0.125
Pc02:159.16.0.124
Pc03:159.16.0.123
Pc04:159.16.0.122
Pc05: 192.168.200.1

2. Subnet mask: 255.255.255.128


En:230313116010

3. Ping a pc in the same subnet from pc03 i.e. pc01.

4. Ping a pc in different subnet i.e. pc02

 It shows that request timed out.


En:230313116010
En:230313116010
En:230313116010
Practical 5

Aim: To configure FTP server on Ubuntu Linux OS

Step 1: Installing VsFTP server in Ubuntu:


 First, we have to update system package sources list and then install VSFTPD binary package as follows
$ sudo apt-get update
$ sudo apt-get install vsftpd

 Once the installation completes, the service will be disabled initially, therefore, we need to start it manually
for the mean time and also enable it to start automatically from the next system boot

 On SystemD
# systemctl start vsftpd
# systemctl enable vsftpd

 On SysVInit
# service vsftpd start
# chkconfig --level 35 vsftpd on

 Next if system has UFW firewall enabled, you have to open ports 20 and 21 where the FTP daemons are
listening, in order to allow access to FTP services from remote machines, then add the new firewall rules as
follows:
$ sudo ufw allow 20/tcp
$ sudo ufw allow 21/tcp
$ sudo ufw status

Step 2 : Configuring and securing VsFTP server in Ubuntu


 For safety purposes, we’ll create a backup file of the original config file /etc/vsftpd/vsftpd.conf
$ sudo cp /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.orig

 Open the config file


$ sudo vi /etc/vsftpd/vsftpd.conf (OR $ sudo nano /etc/vsftpd/vsftpd.conf)

 Add or modify the following options with these values:


anonymous_enable=NO # disable anonymous login
local_enable=YES # permit local logins
write_enable=YES # enable FTP commands which change the filesystem
local_umask=022 # value of umask for file creation for local users
dirmessage_enable=YES # enable showing of messages when users first enter a new directory
xferlog_enable=YES # a log file will be maintained detailing uploads and downloads
connect_from_port_20=YES # use port 20 (ftp-data) on the server machine for PORT style
connections xferlog_std_format=YES # keep standard log file format
listen=NO # prevent vsftpd from running in standalone mode
listen_ipv6=YES # vsftpd will listen on an IPv6 socket instead of an IPv4 one
pam_service_name=vsftpd # name of the PAM service vsftpd will use
userlist_enable=YES # enable vsftpd to load a list of usernames
tcp_wrappers=YES # turn on tcp wrappers

 Now, configure VSFTPD to allow/deny FTP access to users based on the user list file /etc/vsftpd.userlist.
 Note that by default, users listed in userlist_file=/etc/vsftpd.userlist are denied login access with
userlist_deny=YES option if userlist_enable=YES.
En:230313116010
 But, the option userlist_deny=NO twists the meaning of the default setting, so only users whose username is
explicitly listed in userlist_file=/etc/vsftpd.userlist will be allowed to login to the FTP server.
userlist_enable=YES # vsftpd will load a list of usernames, from the filename given by
userlist_file
userlist_file=/etc/vsftpd.userlist # stores usernames.
userlist_deny=NO

 *Important: When users login to the FTP server, they are placed in a chrooted
jail, this is the local root directory which will act as their home directory for the FTP
session only.
 Now add/modify or uncomment these two following options to restrict FTP uses to their home directories.
chroot_local_user = YES
allow_writable_chroot = YES
 The option ‘chroot_local_user = YES’ importantly means local users will be placed in a chroot jail, their
home directory by default after they login. VSFTPD doesn’t allow chroot jail to be writable but however we
can do it by second option ‘allow_writable_chroot = YES’ to disable that default setting.

 Save the changes and restart the VSFTPD services for the changes above to take effect:

 On SystemD
# systemctl restart vsftpd

 On SysVInit
# service vsftpd restart

Step 3: Testing VsFTP server in Ubuntu


 Assume for testing purpose user adds following command

$ sudo useradd -m -c "Aaron Kili, Contributor" -s /bin/bash aaronkilik


$ sudo passwd aaronkilik

 Here, the user aaronkilik in the file /etc/vsftpd.userlist with the echo command and tee command will be
listed explicitly as below

$ echo "aaronkilik" | sudo tee -a /etc/vsftpd.userlist


$ cat /etc/vsftpd.userlist

 Let’s try with anonymous log in then we’ll test with not listed user and then with the listed user. Here
outputs are present in the same order

# ftp 192.168.56.104
Connected to 192.168.56.104 (192.168.56.104).
220 Welcome to FTPexample.com FTP service.
Name (192.168.56.104:aaronkilik) : anonymous
530 Permission denied.
Login failed.
ftp> bye
221 Goodbye.
En:230313116010

# ftp 192.168.56.104
Connected to 192.168.56.104 (192.168.56.104).
220 Welcome to FTPexample.com FTP service.
Name (192.168.56.10:root) : user1
530 Permission denied.
Login failed.
ftp> bye
221 Goodbye.

# ftp 192.168.56.104
Connected to 192.168.56.104 (192.168.56.104).
220 Welcome to FTPexample.com FTP service.
Name (192.168.56.104:aaronkilik) : aaronkilik
331 Please specify the password.
Password:
230 Login successful.
Remote system type is
UNIX.
Using binary mode to transfer files.

 After successful log in user can access the FTP services.

Step 4: Configure FTP User Home Directories in Ubuntu

 open the VSFTPD configuration file once more time.


$ sudo vi /etc/vsftpd.conf

 create the alternative local root directory for the user (aaronkilik, yours is possibly not the same) and set the
required permissions by disabling write permissions to all other users to this directory
$ sudo mkdir /home/aaronkilik/ftp
$ sudo chown nobody:nogroup /home/aaronkilik/ftp
$ sudo chmod a-w /home/aaronkilik/ftp

 Then, create a directory under the local root with the appropriate permissions where the user will store his
files:
$ sudo mkdir /home/aaronkilik/ftp/files
$ sudo chown -R aaronkilk:aaronkilik /home/aaronkilik/ftp/files
$ sudo chmod -R 0770 /home/aaronkilik/ftp/files/
 Afterward add or modify the options below:
user_sub_token=$USER # inserts the username in the local root directory
local_root=/home/$USER/ftp # defines any users local root directory
Save the file and restart the VSFTPD services with recent changes

 At last perform the final check that the user’s local root directory is the FTP directory we created in his home
directory.

 # ftp 192.168.56.104

Connected to 192.168.56.104 (192.168.56.104).


220 Welcome to FTPexample.com FTP service.
En:230313116010
Name (192.168.56.10:aaronkilik) : aaronkilik
331 Please specify the password.
Password:
230 Login successful.
Remote system type is
UNIX.
Using binary mode to transfer files.
ftp> ls

This is how FTP server can be configured on Ubuntu Linux OS.


En:230313116010
Practical 6

Aim: To configure Apache server on Ubuntu Linux OS


Step 1: To installing Apache on Ubuntu

 Apache is available at official Ubuntu software repositories. Update the system’s package index and then
install Apache package.
$ sudo apt update
$ sudo apt install apache2
After successful installation, check important Apache default files and directories
 Main config files directory: /etc/apache2/
 Main config file: /etc/apache2/apache2.conf
 Additional configuration snippets: /etc/apache2/conf-available/ and /etc/apache2/conf-enabled
 Pre-site virtual host configuration snippets: /etc/ apache2/sites-available/ and /etc/apache2/sites-
enabled/.
 Configuration snippets for loading modules: /etc/apache2/mods-available/ and /etc/apache2/mods-
enabled/.
 Web DocumentRoot: /var/www/html/.
 Log files (error and access logs) directory: /var/log/apache/.
 After the Apache installation web-server service should be started automatically, for verification use
command
$ sudo systemct1 status apache2

 Now that your Apache web server up and running, let’s go over some basic management commands to
manage the Apache service using these following commands.
$ sudo systemctl status apache2
$ sudo systemctl stop apache2
$ sudo systemctl start apache2
$ sudo systemctl restart apache2
$ sudo systemctl reload apache2
$ sudo systemctl enable apache2
$ sudo systemctl disable apache2

 Next, if you have the UFW firewall enabled and running on your system, you need to open the ports 80 and
443 to allow client requests to Apache web server via HTTP and HTTPS respectively, then reload the firewall
settings using following commands.
En:230313116010
$ sudo ufw allow 80/tcp
$ sudo ufw allow 443/tcp
$ sudo ufw reload

Step 2: Checking Apache web server on Ubuntu


 Now test if your Apache2 installation is working well; open a web browser and enter the following URL to
access the Apache default web page.
http://domain_name/
OR
http://SERVER_IP/
If you see this page, it means your Apache web server is working fine. It also shows some basic information
about important Apache configuration files and directory locations.

Step 3: Setting up Apache virtual hosts on Ubuntu


 Now we have to create virtual hosts in Apache HTTP server for websites. For our file apacheexmp.com,
hosting it require a virtual host on VPS using Apache /etc/apache2/sites-available/
$sudo mkdir -p /var/www/html/apacheexmp.com/

 Set appropriate permissions on directory as shown:


$ sudo chmod -R 775 /var/www/html/apacheexmp.com/
$ sudo chmod -R www-data:www-data /var/www/html/apacheexmp.com/

 Next, create a test html index page for your site in the root directory of your website.
$ sudo vim /var/www/html/apacheexmp.com/index.html
En:230313116010

Inside, add the following sample HTML code.

<html>
<head>
<title>Welcome to Apacheexmp.com!</title>
</head>
<body>
<h1>The apacheexmp.com virtual host is working!</h1>
</body>
</html>
Save and close the file when you are finished.

 Now create a apacheexmp.com.conf virtual host file for your site under /etc/apache2/sites-
available/ directory.
 $ sudo vim /etc/apache2/sites-available/apacheexmp.com.conf
 Paste in the following configuration directive, which is similar to the default, but updated with new
new directory and domain name.

<VirtualHost *:80>
ServerName apacheexmp.com
ServerAlias www.apacheexmp.com
ServerAdmin [email protected]
DocumentRoot /var/www/html/apacheexmp.com/
ErrorLog ${APACHE_LOG_DIR}/apacheexmp.com_error.log
CustomLog ${APACHE_LOG_DIR}/apacheexmp.com_access.log combined
</VirtualHost>
Save and close the file when you are finished.

 Now enable your site configuration using the a2ensite utility.


$ sudo a2ensite apacheexmp.com.conf

 Next, test your Apache2 config for any errors, if all is Ok, restart the apache2 service, as shown.
$ sudo apache2ctl configtest
$ sudo systemctl restart apache2

 Since the domain name apacheexmp.com is a dummy domain (not a fully registered domain), you also need
to setup local DNS by adding it the /etc/hosts file.
$ sudo vim /etc/hosts
 Then add the following line at the bottom of the file, make sure to replace 192.168.56.101 and
apacheexmp.com with your server’s IP address and local domain name.

 192.168.56.101 apacheexmp.com
 Save the file and exit.

 Finally open a web browser and access the test site’s index page using
 http://apacheexmp.com

 The output will be displaying the text as: “The apacheexmp.com virtual host is working!”
En:230313116010
Practical-7

Aim : To configure static routing using CISCO Packet tracer.

Step 1 : Draw the Topology diagram as mentioned in above diagram.

Step 2 : Assigned IP address on each PC with getway IIP.


En:230313116010
En:230313116010
Step 3: Assign IP address on each Router one by one:

S.NO Device Interface IPv4 Address Subnet mask

FastEthernet0/0 192.168.1.2 255.255.255.0


1. router0
Serial0/0 192.168.4.1 255.255.255.0

FastEthernet0/0 192.168.2.1 255.255.255.0

2. router1 Serial1/0 192.168.5.1 255.255.255.0

Serial0/0 192.168.4.2 255.255.255.0

FastEthernet0/0 192.168.3.5 255.255.255.0

3. Serial1/0 192.168.5.2 255.255.255.0


router 2

Serial0/0 192.168.6.1 255.255.255.0

FastEthernet0/0 192.168.4.6 255.255.255.0


4. router 4
Serial0/0 192.168.6.2 255.255.255.0

Step 4: Now it’s Time to configure Static Route over all those Four Routers R0,R1,R2 and R3
 Ststic Routing Configuration on Router R0:
R0(config)#ip route 192.168.5.0 255.255.255.0 192.168.4.2

R0(config)#ip route 192.168.6.0 255.255.255.0 192.168.4.2

R0(config)#ip route 192.168.4.0 255.255.255.0 192.168.4.2

R0(config)#ip route 192.168.3.0 255.255.255.0 192.168.4.2

R0(config)#ip route 192.168.2.0 255.255.255.0 192.168.4.2

 Static Routing Configuration on Router R1:


R1(config)#ip route 192.168.1.0 255.255.255.0 192.168.4.1

R1(config)#ip route 192.168.6.0 255.255.255.0 192.168.5.2

R1(config)#ip route 192.168.3.0 255.255.255.0 192.168.5.2

R1(config)#ip route 192.168.4.0 255.255.255.0 192.168.5.2


En:230313116010
 Static Routing Configuration on Router R2:

R2(config)#ip route 192.168.4.0 255.255.255.0 192.168.5.1

R2(config)#ip route 192.168.1.0 255.255.255.0 192.168.5.1

R2(config)#ip route 192.168.2.0 255.255.255.0 192.168.5.1

R2(config)#ip route 192.168.4.0 255.255.255.0 192.168.5.1

 Static Routing Configuration on Router R3:

R3(config)#ip route 192.168.1.0 255.255.255.0 192.168.6.1

R3(config)#ip route 192.168.4.0 255.255.255.0 192.168.6.1

R3(config)#ip route 192.168.5.0 255.255.255.0 192.168.6.1

R3(config)#ip route 192.168.2.0 255.255.255.0 192.168.6.1

R3(config)#ip route 192.168.3.0 255.255.255.0 192.168.6.1

 At the and test the communication b/w two PC to test whether your routing is property
configured or not.
 Then ping with another PC:
En:230313116010
En:230313116010

\
En:230313116010
Practical 8

Aim: To configure RIP protocol using CISCO Packet tracer.


Routing Information Protocol (RIP) is an active routing protocol that operates
hop count as a routing metric to find the most suitable route between the
source and the destination network. It is a distance-vector routing protocol that
has an AD value of 120 and works on the Network layer of the OSI model.

 Steps to Configure and Verify Three Router Connections in Cisco Packet


Tracer using RIP Routing:

Step 1: First, open the Cisco packet tracer desktop and select the devices given
below:

S.NO Device Model Name Qty.

1. PC PC 6

2. Switch PT-Switch 3

3. Router PT-router 3

IP Addressing Table:

S.NO Device IPv4 Address Subnet mask Default Gateway

1. PC0 192.168.1.2 255.255.255.0 192.168.1.4

2. PC1 192.168.1.3 255.255.255.0 192.168.1.4

3. PC2 192.168.2.2 255.255.255.0 192.168.2.4

4. PC3 192.168.2.3 255.255.255.0 192.168.2.4

5. PC4 192.168.3.2 255.255.255.0 192.168.3.4

6. PC5 192.168.3.3 255.255.255.0 192.168.3.4


En:230313116010
 Then, create a network topology as shown below the image.
 Use an Automatic connecting cable to connect the devices with others.

Step 2: Configure the PCs (hosts) with IPv4 address and Subnet Mask
according to the IP addressing table given above.
 To assign an IP address in PC0, click on PC0.
 Then, go to desktop and then IP configuration and there you will IPv4
configuration.
 Fill IPv4 address and subnet mask.
En:230313116010
En:230313116010

Step 3: Configure router with IP address and Subnet mask.

IP Addressing Table Router:

S.NO Device Interface IPv4 Address Subnet mask

FastEthernet0/0 192.168.1.4 255.255.255.0

1. router0 Serial0/0 192.168.4.2 255.255.255.0

FastEthernet0/0 192.168.2.4 255.255.255.0

Serial1/0 192.168.4.3 255.255.255.0

2. router1 Serial0/0 192.168.5.2 255.255.255.0

FastEthernet0/0 192.168.3.4 255.255.255.0

3. router2 Serial0/0 192.168.5.3 255.255.255.0

 To assign an IP address in router0, click on router0.


 Then, go to config and then Interfaces.
 Make sure to turn on the ports.
 Then, configure the IP address in Fast Ethernet and serial ports
according to IP addressing Table.
 Fill IPv4 address and subnet mask.
 Repeat the same procedure with other routers to configure them
thoroughly.
En:230313116010

Step 4: After configuring all of the devices we need to assign the routes to
the routers. To assign RIP routes to the particular router:
 First, click on router0 then Go to CLI.
 Then type the commands and IP information given below.
CLI command : network <network id>
 RIP Routes for Router0 are given below:
o Router(config)#network 192.168.1.0
o Router(config)#network 192.168.4.0
En:230313116010

 RIP Routes for Router1 are given below:

o Router(config)#network 192.168.2. 0
o Router(config)#network 192.168.4. 0
o Router(config)#network 192.168.5. 0

 RIP Routes for Router2 are given below:

o Router(config)#network 192.168.3.4
o Router(config)#network 192.168.5.3
En:230313116010

Step 5: Verifying the network by pinging the IP address of any PC.


 We will use the ping command to do so.
 First, click on PC0 then Go to the command prompt.
 Then type ping <IP address of targeted node>.
 As we can see in the below image we are getting replies which
means the connection is working properly.

Example : ping 192.168.2.2

A simulation of the experiment is given below we are sending PDU from PC0 to
PC2 and PC3 to PC5:
En:230313116010
En:230313116010
Practical 9
Aim: To implement packet transfer between two processes using TCP sockets.

Client-Side Programming

Establish a Socket Connection

To connect to another machine we need a socket connection. A socket


connection means the two machines have information about each other’s network
location (IP Address) and TCP port. The java.net.Socket class represents a
Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
 The first argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost,
where code will run on the single stand-alone machine).
 The second argument – TCP Port. (Just a number representing which application to run
on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

Communication
To communicate over a socket connection, streams are used to both input and output the data.

Closing the connection


The socket connection is closed explicitly once the message to the server is sent.
In the program, the Client keeps reading input from a user and sends it to the server until “Over” is
typed.

Java Implementation
// A Java program for a Client
import java.net.*;
import java.io.*;

public class Client


{
// initialize socket and input output streams
private Socket socket = null;

private DataInputStream input = null;


private DataOutputStream out = null;
En:230313116010

// constructor to put ip address and port

public Client(String address, int port)


{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");

// takes input from terminal


input = new DataInputStream(System.in);

// sends output to the socket


out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}

// string to read message from input


String line = "";
En:230313116010
En:230313116010
// keep reading until "Over" is input

while (!line.equals("Over"))
{
try
{

line = input.readLine();
out.writeUTF(line);
}

catch(IOException i)
{
System.out.println(i);
}
}

// close the connection


try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])


{
Client client = new Client("127.0.0.1", 5000);
}
}
En:230313116010
Server Programming

Establish a Socket Connection


To write a server application two sockets are needed.
 A ServerSocket which waits for the client requests (when a client makes a new Socket())
 A plain old Socket to use for communication with the client.

Communication
getOutputStream() method is used to send the output through the socket.

Close the Connection


After finishing, it is important to close the connection by closing the socket as well as
input/output streams.

Java Implementation
// A Java program for a Server
import java.net.*;
import java.io.*;

public class Server


{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;

// constructor with port


public Server(int port)
{
// starts server and waits for a connection
try
En:230313116010
{
server = new ServerSocket(port);
System.out.println("Server started");

System.out.println("Waiting for a client ...");

socket = server.accept();
System.out.println("Client accepted");

// takes input from the client socket


in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));

String line = "";

// reads message from client until "Over" is sent


while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);

}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
En:230313116010
// close
connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])


{
Server server = new Server(5000);
}
}

Important Points
 Server application makes a ServerSocket on a specific port which is 5000. This starts our
Server listening for client requests coming in for port 5000.
 Then Server makes a new Socket to communicate with the client.
socket = server.accept()
 The accept() method blocks(just sits there) until a client connects to the server.
 Then we take input from the socket using getInputStream() method. Our Server keeps
receiving messages until the Client sends “Over”.
 After we’re done we close the connection by closing the socket and the input stream.
 To run the Client and Server application on your machine, compile both of them. Then
first run the server application and then run the Client application.
En:230313116010
To run on Terminal or Command Prompt

 If you’re using Eclipse or likes of such-


 Compile both of them on two different terminals or tabs
 Run the Server program first
 Then run the Client program
 Type messages in the Client Window which will be received and shown by the Server
Window simultaneously.
 Type Over to end.
En:230313116010
Practical 10
Aim: To implement packet transfer between two processes using UDP sockets
 Datagram Sockets are Java’s mechanism for network communication
via UDP instead of TCP.
 Java provides Datagram Socket to communicate over UDP instead of
TCP. It is also built on top of IP.
 Datagram Sockets can be used to both send and receive packets over the
Internet.
 One of the examples where UDP is preferred over TCP is the live
coverage of TV channels. In this aspect, we want to transmit as many
frames to live audience as possible not worrying about the loss of one or
two frames.
 TCP being a reliable protocol add its own overhead while transmission.
Another example where UDP is preferred is online multiplayer gaming.
 In games like counter-strike or call of duty, it is not necessary to relay all
the information but the most important ones.
 It should also be noted that most of the applications in real life uses careful
blend of both UDP and TCP; transmitting the critical data over TCP and
rest of the data via UDP.
 This article is a simple implementation of one-sided client-server program
wherein the client sends messages to server and server just prints it until
the client sends “bye”.

Client Side Implementation


// Java program to illustrate Client side
// Implementation using DatagramSocket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class udpBaseClient_2


{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(System.in);

// Step 1:Create the socket object for


// carrying the data.
DatagramSocket ds = new DatagramSocket();

InetAddress ip =
InetAddress.getLocalHost(); byte buf[] =
null;

// loop while user not enters "bye"


En:230313116010
while (true)
{
String inp = sc.nextLine();

// convert the String input into the byte array.


buf = inp.getBytes();

// Step 2 : Create the datagramPacket for sending


// the data.
DatagramPacket DpSend
=
new DatagramPacket(buf, buf.length, ip, 1234);

// Step 3 : invoke the send call to actually send


// the data.
ds.send(DpSend);

// break the loop if user enters


"bye" if (inp.equals("bye"))
break;
}
}
}

Server side Implementation


// Java program to illustrate Server side
// Implementation using DatagramSocket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class udpBaseServer_2


{
public static void main(String[] args) throws IOException
{
// Step 1 : Create a socket to listen at port 1234
DatagramSocket ds = new DatagramSocket(1234);
byte[] receive = new byte[65535];
DatagramPacket DpReceive =
null; while (true)
{
// Step 2 : create a DatgramPacket to receive the data.
DpReceive = new DatagramPacket(receive, receive.length);

// Step 3 : revieve the data in byte buffer.


ds.receive(DpReceive);

System.out.println("Client:-" + data(receive));
En:230313116010

// Exit the server if the client sends


"bye" if
(data(receive).toString().equals("bye"))
{
System.out.println("Client sent bye...EXITING");
break;
}

// Clear the buffer after every message.


receive = new byte[65535];
}
}

// A utility method to convert the byte array


// data into a string representation.
public static StringBuilder data(byte[]
a)
{
if (a == null)
return null;
StringBuilder ret = new
StringBuilder(); int i = 0;
while (a[i] != 0)
{
ret.append((char)
a[i]); i++;
}
return ret;
}
}

 To run on Terminal or Command Prompt


En:230313116010

***

You might also like