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

Computer Networks Lab Record 2021(1) (1)

Uploaded by

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

Computer Networks Lab Record 2021(1) (1)

Uploaded by

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

INDEX

S.No. Date Name Of The Experiment Marks Signature

Basic commands using a network protocol


1
analyzer.

2. HTTP web client program using TCP


sockets.
3.A Echo client and echo server.

3.B Chat Application.

3.C File Transfer Application.

4. Simulation of DNS using UDP sockets.

Address Resolution Protocol (ARP) using


5.A
TCP

5.B Reverse Address Resolution Protocol


(RARP) using UDP

6. Study of Network Simulator

Study of TCP/UDP Performance using


7.
Simulation Tool

8.
Simulation of Distance Vector/Link State
Routing.

Performance Comparison Of Routing


9.
Protocols

10. Simulation of Error Correction Code(CRC)


EX.NO:1
Basic commands using a network protocol analyzer
Date:

AIM:
To Learn to use commands like Wireshark, tcpdump, netstat, ifconfig, nslookup and
traceroute

1. Wireshark
Wireshark is a packet sniffer and analysis tool. It captures network traffic on the
local network and stores that data for offline analysis. Wireshark captures network
traffic from Ethernet, Bluetooth, Wireless (IEEE. 802.11), Token Ring, Frame Relay
connections, and more

Usage:

# wireshark

Or

Open wireshark from menu.

Select Any interface listed below:


It will start sniffing

2. Tcpdump:

The tcpdump utility allows you to capture packets that flow within your network to
assist in network troubleshooting. The following are several examples of using
tcpdump with different options. Traffic is captured based on a specified filter.
Options Description
-D Print a list of network interfaces.
Specify an interface on which to
-i
capture.
Specify the number of packets to
-c
receive.
-v, -vv, -vvv Increase the level of detail (verbosity).
-w Write captured data to a file.
-r Read captured data from a file.

Many other options and


arguments can be used with tcpdump. The following are some specific examples of the power
of the tcpdump utility.

1. Display traffic between 2 hosts

To display all traffic between two hosts (represented by variables host1 and host2):

# tcpdump host host1 and host2

2. Display traffic from a source or destination host only

To display traffic from only a source (src) or destination (dst) host:

# tcpdump src host


# tcpdump dst host
3. Display traffic for a specific protocol

Provide the protocol as an argument to display only traffic for a specific protocol, for
example tcp, udp, icmp, arp:

# tcpdump protocol

For example to display traffic only for the tcp traffic :

# tcpdump tcp
4. Filtering based on source or destination port

To filter based on a source or destination port:

# tcpdump src port ftp

# tcpdump dst port http

2. Netstat:

Netstat is a common command line TCP/IP networking available in most versions of


Windows, Linux, UNIX and other operating systems. Netstat provides information and
statistics about protocols in use and current TCP/IP network connections.

The Windows help screen (analogous to a Linux or UNIX for netstat reads as follows:

Displays protocol statistics and current TCP/IP network connections.

NETSTAT -a -b -e -n -o -p proto -r -s -v interval

-a Displays all connections and listening ports.


Displays the executable involved in creating each connection or listening port. In
some cases well-known executables host multiple independent components, and in
these cases the sequence of components involved in creating the connection or
-b
listening port is displayed. In this case the executable name is in [] at the bottom, on
top is the component it called, and so forth until TCP/IP was reached. Note that this
option can be time-consuming and will fail unless you have sufficient permissions.
-e Displays Ethernet statistics. This may be combined with the -s option.
-n Displays addresses and port numbers in numerical form.
-o Displays the owning process ID associated with each connection.

Shows connections for the protocol specified by proto; proto may be any of: TCP,
-p proto UDP, TCPv6, or UDPv6. If used with the -s option to display per-protocol statistics,
proto may be any of: IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
-r Displays the routing table.
Displays per-protocol statistics. By default, statistics are shown for IP, IPv6, ICMP,
-s ICMPv6, TCP, TCPv6, UDP, and UDPv6; the -p option may be used to specify a subset
of the default.
When used in conjunction with -b, will display sequence of components involved in
-v
creating the connection or listening port for all executables.
Redisplays selected statistics, pausing interval seconds between each display. Press
interval CTRL+C to stop redisplaying statistics. If omitted, netstat will print the current
configuration information once.

Syntax

netstat [-a] [-e] [-n] [-o] [-p Protocol] [-r] [-s] [Interval]

Parameters

Used without
displays active TCP connections.
parameters

Displays all active TCP connections and the TCP and UDP ports on which the
-a
computer is listening.
Displays Ethernet statistics, such as the number of bytes and packets sent and
-e
received. This parameter can be combined with -s.

Displays active TCP connections, however, addresses and port numbers are
-n
expressed numerically and no attempt is made to determine names.

Displays active TCP connections and includes the process ID (PID) for each
-o connection. You can find the application based on the PID on the Processes tab
in Windows Task Manager. This parameter can be combined with -a, -n, and -p.

Shows connections for the protocol specified by Protocol. In this case, the
Protocol can be tcp, udp, tcpv6, or udpv6. If this parameter is used with -s to
-p
display statistics by protocol, Protocol can be tcp, udp, icmp, ip, tcpv6, udpv6,
icmpv6, or ipv6.

Displays statistics by protocol. By default, statistics are shown for the


TCP, UDP, ICMP, and IP protocols. If the IPv6 protocol for Windows XP is
-s installed, statistics are shown for the TCP over IPv6, UDP over IPv6,
ICMPv6, and IPv6 protocols. The -p parameter can be used to specify a
set of protocols.
Displays the contents of the IP routing table. This is equivalent to the
-r
route print command.
Redisplays the selected information every Interval seconds. Press
Interval CTRL+C to stop the redisplay. If this parameter is omitted, netstat prints
the selected information only once.
--help - Displays help at the command prompt.

3. IfconfigL:

In Linux, ifconfig is a cmd line utility designed to run from the linux command prompt.
This utility allows you to get the IP address information of a linux computer. It also allows
some control over active TCP/IP connections.

Using ifconfig

From the terminal, type ifconfig to run the utility with default options. The output of the
default command contains the IP address, network mask, and gateway for all physical and
virtual network adapter
SYNOPSIS:

ifconfig [-v] [-a] [-s] [interface]


ifconfig [-v] interface [aftype] options | address ...
OPTIONS
-a display all interfaces which are currently available, even
if down

-s display a short list (like netstat -i)

-v be more verbose for some error conditions


interface
The name of the interface.

up This flag causes the interface to be activated.

down This flag causes the driver for this interface to be shut
down.
Eg: Ifconfig –a (to see all the interfaces)

4. Nslookup:
The nslookup (which stands for name server lookup) command is a network utility
program used to obtain information about internet servers. It finds name server information
for domains by querying the Domain Name System.

5. Traceroute :

Traceroute is a network diagnostic tool used to track the pathway taken by a packet
on an IP network from source to destination. Traceroute also records the time taken for each
hop the packet makes during its route to the destination.

Traceroute uses Internet Control Message Protocol (ICMP) echo packets with variable time to
live (TTL) values. The response time of each hop is calculated. To guarantee accuracy, each
hop is queried multiple times (usually three times) to better measure the response of that
particular hop.

# tracert www.google.com

With the tracert command shown above, we're asking tracert to show us the path from the
local computer all the way to the network device with the hostname www.google.com.
Result:
Thus the Basic commands using a network protocol analyzer was implemented
successfully.
EX.NO: 2
HTTP web client program to download a web page using TCP sockets.
Date:

Aim:
To write a python program for socket for HTTP for web page download

Algorithm:
1.Start the program.

2.To create the frame based on the user request.

3.To send frames to server from the client side.

4.If your frames reach the server it will send ACK signal to client otherwise it will send NACK
signal to client.

5.Stop the program

Program:
#!/usr/bin/env python3

import requests

import sys

# Using the request function to fetch data from the webpage

response = requests.get(sys.argv[1])

# The status code of the webpage

print("<Response>")

print (response.status_code)

# the Actual response

# Usage: # Python websock.py https://<site> or http://<site> or <ip>

print (response.content)
Output:
Before running these programs type the below commands

# pip3 install requests

# Python3 webclient.py https://google.com

Result:
Thus the program for creating sockets for HTTP web page download was
implemented
EX.NO: 3(A)
Applications using TCP sockets like Echo client and Echo server
Date:

Aim:
To write a python program for application using TCPSockets Links

Algorithm:

1.Start the program.


2.Get the frame size from the user
3.To create the framebased on the user request.
4.To send frames to server from the client side.
5.If your frames reach the server it will send ACK signal to client
otherwise it will send NACK signal to client.
6.Stop the program

EchoServer.py

#!/usr/bin/env python3

#Echo server

import socket

import sys

server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server_address=('localhost', 10000)

server.bind(server_address)

server.listen(1)

print('Waiting for a connection')

connection,client_address = server.accept()

print("Connection established:", client_address)

data = connection.recv(1000)

print("received: ", data)

connection.sendall(data)

connection.close()

server.close()
Echoclient.py

#!/usr/bin/env python3

#Echo Client

import socket

import sys

client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server_address=('localhost', 10000)

client.connect(server_address)

message=input()

print("Sending ",message)

client.sendall(message.encode())

print("Original:",message)

data = client.recv(1000).decode()

print("Echo:",data)

client.close()
Output:

Client:

#python3 echoclient.py
Hai
Sending hi
Original: hi
Echo: hi

Server:

#python echoserver.py
Waiting for a connection
Connection established: ('127.0.0.1', 57094)
received: b'hi'

Result:
Thus the python program to concurrently communicate using TCP Sockets was
executed successfully
EX.NO: 3(B)
CHAT Applications
Date:

AIM:

To implement a CHAT application, where the Client establishes a connection with


the Server. The Client and Server can send as well as receive messages at the same time.
Both the Client and Server exchange messages

Concept:
1. It uses TCP socket communication .We have a server as well as a client.
2. Both can be run in the same machine or different machines. If both are running in
the m achine, the address to be given at the client side is local host address.
3. If both are running in different machines, then in the client side we need to specify
the ip address of machine in which server application is running

Chatserver.py

#!/usr/bin/env python3
import socket
import sys
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_address=('localhost', 10000)
server.bind(server_address)
server.listen(1)
print("Waiting for the connections")
connection,client_address=server.accept()
print("Connection established with",client_address)
message=""
while message!="end":
data=connection.recv(1000).decode()
if data:
print(data)
message=input()
connection.sendall(message.encode())
else:
break
connection.close()
server.close()
Chatclient.py

#!/usr/bin/env python3
import socket
import sys
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_address = ('localhost',10000)
client.connect(server_address)
print("Connecting to port",server_address)
message=input()
client.sendall(message.encode())
while message!='end':
data=client.recv(1000).decode()
if data:
print(data)
message=input()
client.sendall(message.encode())
else:
break
client.close()
OUTPUT:

Result:
Thus the python program to create chat application using TCP Sockets was executed
successfully
EX.NO: 3(C)
File Transfer
Date:

AIM:
To write a python program for file transfer using TCP Sockets.
Algorithm:
Server:

Step1: Import python packages and create file server.


Step2: Create a new server socket and bind it to the port.
Step3: Accept the client connection
Step4: Get the file name and stored into the BufferedReader.
Step5: Create a new object class file and realine.
Step6: If file is exists then FileReader read the content until EOF is reached.
Step7: Stop the program.
Client:

Step1: Import python library and create class file server.


Step2: Create a new server socket and bind it to the port.
Step3: Now connection is established.
Step4: The object of a BufferReader class is used for storing data content which has
been retrieved from socket object.
Step5: The content of file is displayed in the client window and the connection is
close
Step6: Stop the program.

Program:
File Client:
#!/usr/bin/env python3

Import socket

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

host = input(str("Enter the Host address of the sender : "))

port = 8080

s.connect((host,port))

print("Connected ...")

filename = input(str("Enter a Filename for the Incoming file : "))

file = open(filename, 'wb')

file_data = s.recv(1024)

file.write(file_data)

file.close()

print("File has been received successfully...")


Server:
#!/usr/bin/env python

import socket

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

host = '127.0.0.1' #socket.gethostname()

port = 8080

s.bind((host,port))

s.listen(1)

print(host)

print("Waiting for any incoming connections ..")

conn, addr = s.accept()

print(addr, "has connected to server")

filename = input(str("Enter the name of the file : "))

file = open(filename, 'rb')

file_data = file.read(1024)

conn.send(file_data)

print("Data has been transmitted successfully")


Output:
Server:

# python3 fileserver.py
127.0.0.1
Waiting for incoming connecition ..

Client:
#python3 fileclient.py
Enter the Host address of the sender : 127.0.0.1
Connected..
Enter the filename for the incoming file : file.txt

Server:
# python3 fileserver.py
127.0.0.1
Waiting for incoming connecition ..
('127.0.0.1', 44668) has connected to server
Enter the name of the file :file2.txt

RESULT:
Thus the python program file transfer application using TCP Sockets was executed
EX.NO: 4
Simulation of DNS using UDP sockets.
Date:

Aim:
Write python program Simulation of DNS using UDP Sockets

Algorithm:
1.Start the program.
2.To send frames to server from the client side.
3.If your frames reach the server it will send ACK signal to client
otherwise it will send NACK signal to client.
4.Stop the program
Program:

UDP DNS Server:


Udpdnsserver.py

#!/usr/bin/env python3

import socket

dns_table = {"www.google.com":"192.168.1.2",

"www.youtube.com":"192.168.1.3",

"www.facebook.com":"192.168.1.4",

"www.bing.com":"192,168.1.5"}

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print ("DNS Server : Running")

s.bind(("127.0.0.1",53))

while True:

data, address = s.recvfrom(1024)

print(f"{address} wants to fetch data!")

data = data.decode()

ip = dns_table.get(data, "Not Found!").encode()

send = s.sendto(ip,address)
UDP DNS Client:
Udpdnsclient.py

#!/usr/bin/env python3

import socket

hostname = socket.gethostname()

ipaddr = "127.0.0.1"

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

addr = (ipaddr, 53)

c = "Y"

while c.upper() == "Y":

req_domain = input("Enter domain name for which the ip is needed:")

send = s.sendto(req_domain.encode(), addr)

data,address = s.recvfrom(1024)

reply_ip = data.decode().strip()

print (f"The IP for the Domain name {req_domain}:{reply_ip}")

c = (input("Continue? (y/n)"))

s.close()
OUTPUT:
Server:
#python3 udpdnsserver.py
Dnsserver : Running

Client:
#python3 udpclient.py
Enter domain name for which the ip is needed : www.facebook.com

Result:
Thus the DNS application program was executed.
EX.NO: 5(A)
Program for Address Resolution Protocol (ARP) using TCP
Date:

Aim:
To write a python program for simulating ARP protocols using TCP
ALGORITHM:
Client:

1. Start the program


2. Using socket connection is established between client and server.
3. Get the IP address to be converted into MAC address.
4. Send this IP address to server.
5. Server returns the MAC address to client.
Server:

1. Start the program


2. Accept the socket which is created by the client.
3. Server maintains the table in which IP and corresponding MAC addresses are
stored.
4. Read the IP address which is send by the client.
5. Map the IP address with its MAC address and return the MAC address to client.
Program:
Client:
#!/usr/bin/env python3

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.connect(('localhost',1234))

a=input("ARP:")

add=input("Enter IP:")

s.send(add.encode())

mac=s.recv(1024)

mac=mac.decode("utf-8")

if(a=="ARP"):

print('MAC of',add,'is: ',mac)


Server:

#!/usr/bin/env python3

import socket

table={

'192.168.1.1':'AA:AA:AA:AA:AA:AA',

'192.168.1.2':'BB:BB:BB:BB:BB:BB',

'192.168.1.3':'CC:CC:CC:CC:CC:CC',

'192.168.1.4':'DD:DD:DD:DD:DD:DD',

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.bind(('127.0.0.1',1234))

s.listen()

clientsocket,address = s.accept()

print("Connection From ", address,"Has Established")

ip = clientsocket.recv(1024)

ip = ip.decode("utf-8")

mac = table.get(ip,"Address not found")

clientsocket.send(mac.encode())
Output:
Server:
#python3 arpserver.py
Connection From ('127.0.0.1', 59310) Has Established

Client:
#python3 arpclient.py
Enter IP: 192.168.1.1
MAC of 192.168.1.1 is: AA: AA: AA: AA: AA: AA

Result:
Thus a python program for simulating ARP protocols is executed successfully.
EX.NO: 5(B)
Program for Address Resolution Protocol (RARP) using TCP
Date:

Aim:
To write a python program for simulating RARP protocols using TCP
ALGORITHM:
Client:

1. Start the program


2. Using socket connection is established between client and server.
3. Get the MAC address to be converted into IP address.
4. Send this MAC address to server.
5. Server returns the IP address to client.
Server:

1. Start the program


2. Accept the socket which is created by the client.
3. Server maintains the table in which MAC and corresponding IP addresses are
stored.
4. Read the MAC address which is send by the client.
5. Map the MAC address with its IP address and return the IP address to client.
Program:
Client:
#!/usr/bin/env python3

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.connect(('localhost',1234))

a=input("ARP:")

add=input("Enter MAC:")

s.send(add.encode())

mac=s.recv(1024)

mac=mac.decode("utf-8")

print('IP of',add,'is: ',mac)


Server:

#!/usr/bin/env python3

import socket

table={

'AA:AA:AA:AA:AA:AA':'192.168.1.1',

'BB:BB:BB:BB:BB:BB':'192.168.1.2',

'CC:CC:CC:CC:CC:CC':'192.168.1.3',

'DD:DD:DD:DD:DD:DD':'192.168.1.4'

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.bind(('127.0.0.1',1234))

s.listen()

clientsocket,address = s.accept()

print("Connection From ", address,"Has Established")

ip = clientsocket.recv(1024)

ip = ip.decode("utf-8")

mac = table.get(ip,"Address not found")

clientsocket.send(mac.encode())
Output:
Server:
#python3 arpserver.py
Connection from ('127.0.0.1', 59310) Has Established

Client:
#python3 arpclient.py
Enter MAC: AA: AA: AA: AA: AA: AA
IP of AA: AA: AA: AA: AA: AA is: 192.168.1.1

Result:
Thus a python program for simulating RARP protocols is executed successfully.
EX.NO: 6
Study of Network Simulator
Date:

 Ns programming: A Quick start


 Case study I: A simple Wireless network
 Case study II: Create a new agent in Ns
 Ns Status
 Periodical release (ns-2.26, Feb 2003)
 Platform support
 FreeBSD, Linux, Solaris, Windows and Mac

Ns Functionalities:
Routing, Transportation, Traffic sources, queuing disciplines, QoS.
Wireless:
Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various
utilities NS(Network Simulators) Most of the commercial simulators are GUI driven, while
some network simulators are CLI driven. The network model / configuration describe the
state of the network (nodes, routers, switches and links) and the events (data
transmissions, packet error etc.). The important outputs of simulations are the trace files.
Trace files log every packet, every event that occurred in the simulation and are used for
analysis. Network simulators can also provide other tools to facilitate visual analysis
of trends and potential trouble spots.

Most network simulators use discrete event simulation, in which a list of pending
"events" is stored, and those events are processed in order, with some events triggering
future events such as the event of the arrival of a packet at one node triggering the event
of the arrival of that packet at a downstream node. Simulation of networks is a very
complex task. For example, if congestion is high, then estimation of the average occupancy
is challenging because of high variance. To estimate the likelihood of a buffer overflow in
a network, the time required for an accurate answer can be extremely large. Specialized
techniques such as "control variants" and "importance sampling" have been
developed to speed Simulation.

Examples of network simulators:


There are many both free/open-source and proprietary network simulators.
Examples of notable network simulation software are, ordered after how often they are
mentioned in research papers:
 ns (open source)
 OPNET (proprietary software)
 NetSim (proprietary software)
Uses of network simulators:
Network simulators serve a variety of needs. Compared to the cost and time
involved in setting up an entire test bed containing multiple networked computers, routers
and data links, network simulators are relatively fast and inexpensive. They allow
engineers, researchers to test scenarios that might be particularly difficult or expensive
to emulate using real hardware - for instance, simulating a scenario with several nodes
or experimenting with a new protocol in the network. Network simulators are particularly
useful in allowing researchers to test new networking protocols or changes to existing
protocols in a controlled and reproducible environment. A typical network simulator
encompasses a wide range of networking technologies and can help the users to build
complex networks from basic building blocks such as a variety of nodes and links. With
the help of simulators, one can design hierarchical networks using various types of nodes
like computers, hubs, bridges, routers, switches, links, mobile units etc. Various types of
Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and Local Area Network
(LAN) technologies like Ethernet, token rings etc., can all be simulated with a typical
simulator and the user can test, analyses various standard results apart from devising some
novel protocol or strategy for routing etc. Network simulators are also widely used
to simulate battlefield networks in Network-centric warfare There are a wide variety of
network simulators, ranging from the very simple to the very complex. Minimally, a
network simulator must enable a user to represent a network topology, specifying the
nodes on the network, the links between those nodes and the traffic between the nodes.
More complicated systems may allow the user to specify everything about the protocols
used to handle traffic in a network. Graphical applications allow users to easily visualize
the workings of their simulated environment. Text-based applications may provide a less
intuitive interface, but may permit more advanced forms of customization.

Packet loss occurs when one or more packets of data travelling across a computer
network fail to reach their destination. Packet loss is distinguished as one of the three main
error types encountered in digital communications; the other two being bit error and
spurious packets caused due to noise. Packets can be lost in a network because they
may be dropped when a queue in the network node overflows. The amount of packet
loss during the steady state is another important property of a congestion control
scheme. The larger the value of packet loss, the more difficult it is for transport layer
protocols to maintain high bandwidths, the sensitivity to loss of individual packets, as
well as to frequency and patterns of loss among longer packet sequences is strongly
dependent on the application itself.

Throughput:
This is the main performance measure characteristic, and most widely used In
communication networks, such as Ethernet or packet radio, throughput or network
throughput is the average rate of successful message delivery over a communication
channel. The throughput is usually measured in bits per second (bit/s or bps), and
sometimes in data packets per second or data packets per time slot This measure how soon
the receiver is able to get a certain amount of data send by the sender. It is determined
as the ratio of the total data received to the end to end delay. Throughput is an important
factor which directly impacts the network performance
Delay:

Delay is the time elapsed while a packet travels from one point e.g., source
premise or network ingress to destination premise or network degrees. The larger the
value of delay, the more difficult it is for transport layer protocols to maintain high band
widths. We will calculate end to end delay

Queue Length:
A queuing system in networks can be described as packets arriving for service,
waiting for service if it is not immediate, and if having waited for service, leaving the
system after being served. Thus queue length is very important characteristic to
determine that how well the active queue management of the congestion control
algorithm has been working.

Result:
Thus the study of network Simulator has studied successfully.
EX.NO: 7
Study of TCP/UDP Performance using Simulation Tool
Date:

Aim:
To Study of TCP/UDP Performance using Simulation Tool.
CASE STUDY – 1 TCP:

The transmission Control Protocol (TCP) is one of the most important protocols of
Internet Protocols suite. It is most widely used protocol for data transmission in
communication network such as internet.

Features:

 TCP is reliable protocol. That is, the receiver always sends either positive or negative
acknowledgement about the data packet to the sender, so that the sender always has
bright clue about whether the data packet is reached the destination or it needs to
resend it.
 TCP ensures that the data reaches intended destination in the same order it was sent.
 TCP is connection oriented. TCP requires that connection between two remote points
be established before sending actual data.
 TCP provides error-checking and recovery mechanism.
 TCP provides end-to-end communication.
 TCP provides flow control and quality of service.
 TCP operates in Client/Server point-to-point mode.
 TCP provides full duplex server, i.e. it can perform roles of both receiver and sender.

Header:

The length of TCP header is minimum 20 bytes long and maximum 60 bytes.

 Source Port (16-bits) - It identifies source port of the application process on the sending
device.
 Destination Port (16-bits) - It identifies destination port of the application process on the
receiving device.
 Sequence Number (32-bits) - Sequence number of data bytes of a segment in a session.
 Acknowledgement Number (32-bits) - When ACK flag is set, this number contains the
next sequence number of the data byte expected and works as acknowledgement of the
previous data received.
 Data Offset (4-bits) - This field implies both, the size of TCP header (32-bit words) and the
offset of data in current packet in the whole TCP segment.
 Reserved (3-bits) - Reserved for future use and all are set zero by default.
 Flags (1-bit each)
o NS - Nonce Sum bit is used by Explicit Congestion Notification signaling process.
o CWR - When a host receives packet with ECE bit set, it sets Congestion Windows
Reduced to acknowledge that ECE received.
o ECE -It has two meanings:
 If SYN bit is clear to 0, then ECE means that the IP packet has its CE
(congestion experience) bit set.
 If SYN bit is set to 1, ECE means that the device is ECT capable.
o URG - It indicates that Urgent Pointer field has significant data and should be
processed.
o ACK - It indicates that Acknowledgement field has significance. If ACK is cleared to
0, it indicates that packet does not contain any acknowledgement.
o PSH - When set, it is a request to the receiving station to PUSH data (as soon as it
comes) to the receiving application without buffering it.
o RST - Reset flag has the following features:
 It is used to refuse an incoming connection.
 It is used to reject a segment.
 It is used to restart a connection.
o SYN - This flag is used to set up a connection between hosts.
o FIN - This flag is used to release a connection and no more data is exchanged
thereafter. Because packets with SYN and FIN flags have sequence numbers, they
are processed in correct order.
 Windows Size - This field is used for flow control between two stations and indicates the
amount of buffer (in bytes) the receiver has allocated for a segment, i.e. how much data is
the receiver expecting.
 Checksum - This field contains the checksum of Header, Data and Pseudo Headers.
 Urgent Pointer - It points to the urgent data byte if URG flag is set to 1.
 Options - It facilitates additional options which are not covered by the regular header.
Option field is always described in 32-bit words. If this field contains data less than 32-bit,
padding is used to cover the remaining bits to reach 32-bit boundary.

Addressing:

TCP communication between two remote hosts is done by means of port numbers (TSAPs).
Ports numbers can range from 0 – 65535 which are divided as:

 System Ports (0 – 1023)


 User Ports ( 1024 – 49151)
 Private/Dynamic Ports (49152 – 65535)
Connection Management:

TCP communication works in Server/Client model. The client initiates the connection and the
server either accepts or rejects it. Three-way handshaking is used for connection
management.

Establishment:

Client initiates the connection and sends the segment with a Sequence number.
Server acknowledges it back with its own Sequence number and ACK of client’s segment
which is one more than client’s Sequence number. Client after receiving ACK of its segment
sends an acknowledgement of Server’s response.

Release:

Either of server and client can send TCP segment with FIN flag set to 1. When the
receiving end responds it back by Acknowledging FIN, that direction of TCP communication is
closed and connection is released.

Bandwidth Management:

TCP uses the concept of window size to accommodate the need of Bandwidth
management. Window size tells the sender at the remote end, the number of data byte
segments the receiver at this end can receive. TCP uses slow start phase by using window size
1 and increases the window size exponentially after each successful communication.

For example, the client uses windows size 2 and sends 2 bytes of data. When the
acknowledgement of this segment received the windows size is doubled to 4 and next sent
the segment sent will be 4 data bytes long. When the acknowledgement of 4-byte data
segment is received, the client sets windows size to 8 and so on.

If an acknowledgement is missed, i.e. data lost in transit network or it received NACK,


then the window size is reduced to half and slow start phase starts again.
Error Control &and Flow Control:

TCP uses port numbers to know what application process it needs to handover the
data segment. Along with that, it uses sequence numbers to synchronize itself with the
remote host. All data segments are sent and received with sequence numbers. The Sender
knows which last data segment was received by the Receiver when it gets ACK. The Receiver
knows about the last segment sent by the Sender by referring to the sequence number of
recently received packet.

If the sequence number of a segment recently received does not match with the
sequence number the receiver was expecting, then it is discarded and NACK is sent back. If
two segments arrive with the same sequence number, the TCP timestamp value is compared
to make a decision.

Multiplexing:

The technique to combine two or more data streams in one session is called
Multiplexing. When a TCP client initializes a connection with Server, it always refers to a well-
defined port number which indicates the application process. The client itself uses a randomly
generated port number from private port number pools.

Using TCP Multiplexing, a client can communicate with a number of different


application process in a single session. For example, a client requests a web page which in
turn contains different types of data (HTTP, SMTP, FTP etc.) the TCP session timeout is
increased and the session is kept open for longer time so that the three-way handshake
overhead can be avoided.

This enables the client system to receive multiple connection over single virtual
connection. These virtual connections are not good for Servers if the timeout is too long.

Congestion Control:

When large amount of data is fed to system which is not capable of handling it,
congestion occurs. TCP controls congestion by means of Window mechanism. TCP sets a
window size telling the other end how much data segment to send. TCP may use three
algorithms for congestion control:

 Additive increase, Multiplicative Decrease


 Slow Start
 Timeout React

Timer Management:

TCP uses different types of timer to control and management various tasks:

Keep-alive timer:

 This timer is used to check the integrity and validity of a connection.


 When keep-alive time expires, the host sends a probe to check if the connection still
exists.

Retransmission timer:

 This timer maintains stateful session of data sent.


 If the acknowledgement of sent data does not receive within the Retransmission time,
the data segment is sent again.

Persist timer:

 TCP session can be paused by either host by sending Window Size 0.


 To resume the session a host needs to send Window Size with some larger value.
 If this segment never reaches the other end, both ends may wait for each other for
infinite time.
 When the Persist timer expires, the host re-sends its window size to let the other end
know.
 Persist Timer helps avoid deadlocks in communication.

Timed-Wait:

 After releasing a connection, either of the hosts waits for a Timed-Wait time to
terminate the connection completely.
 This is in order to make sure that the other end has received the acknowledgement of
its connection termination request.
 Timed-out can be a maximum of 240 seconds (4 minutes).

Crash Recovery:

TCP is very reliable protocol. It provides sequence number to each of byte sent in
segment. It provides the feedback mechanism i.e. when a host receives a packet, it is bound
to ACK that packet having the next sequence number expected (if it is not the last segment).

When a TCP Server crashes mid-way communication and re-starts its process it sends
TPDU broadcast to all its hosts. The hosts can then send the last data segment which was
never unacknowledged and carry onwards.
CASE STUDY – 2 UDP:

The User Datagram Protocol (UDP) is simplest Transport Layer communication


protocol available of the TCP/IP protocol suite. It involves minimum amount of
communication mechanism. UDP is said to be an unreliable transport protocol but it uses IP
services which provides best effort delivery mechanism.

In UDP, the receiver does not generate an acknowledgement of packet received and in
turn, the sender does not wait for any acknowledgement of packet sent. This shortcoming
makes this protocol unreliable as well as easier on processing.

Requirement of UDP:

A question may arise, why do we need an unreliable protocol to transport the data? We
deploy UDP where the acknowledgement packets share significant amount of bandwidth
along with the actual data. For example, in case of video streaming, thousands of packets are
forwarded towards its users. Acknowledging all the packets is troublesome and may contain
huge amount of bandwidth wastage. The best delivery mechanism of underlying IP protocol
ensures best efforts to deliver its packets, but even if some packets in video streaming get
lost, the impact is not calamitous and can be ignored easily. Loss of few packets in video and
voice traffic sometimes goes unnoticed.

Features:

 UDP is used when acknowledgement of data does not hold any significance.
 UDP is good protocol for data flowing in one direction.
 UDP is simple and suitable for query based communications.
 UDP is not connection oriented.
 UDP does not provide congestion control mechanism.
 UDP does not guarantee ordered delivery of data.
 UDP is stateless.
 UDP is suitable protocol for streaming applications such as VoIP, multimedia
streaming.

UDP Header

UDP header is as simple as its function.

UDP header contains four main parameters:

 Source Port - This 16 bits information is used to identify the source port of the packet.
 Destination Port - This 16 bits information, is used identify application level service on
destination machine.
 Length - Length field specifies the entire length of UDP packet (including header). It is
16-bits field and minimum value is 8-byte, i.e. the size of UDP header itself.
 Checksum - This field stores the checksum value generated by the sender before
sending. IPv4 has this field as optional so when checksum field does not contain any
value it is made 0 and all its bits are set to zero.

UDP application:

Here are few applications where UDP is used to transmit data:

 Domain Name Services


 Simple Network Management Protocol
 Trivial File Transfer Protocol
 Routing Information Protocol
 Kerbero

Result:
Thus the study of TCP/UDP Performance using simulation tool has studied successfully.
EX.NO: 8
Simulation of Distance Vector/Link State Routing.
Date:

(A) LINK STATE ROUTING:


Aim:
To study the link state routing flooding and distance vector routing.

Link State routing:


Routing is the process of selecting best paths in a network. In the past, the term
routing was also used to mean forwarding network traffic among networks. However this
latter function is much better described as simply forwarding. Routing is performed for
many kinds of networks, including the telephone network (circuit switching), electronic
data networks (such as the Internet), and transportation networks. This article is
concerned primarily with routing in electronic data networks using packet switching
technology .In packet switching networks, routing directs packet forwarding (the transit of
logically addressed network packets from their source toward their ultimate destination)
through intermediate nodes. Intermediate nodes are typically network hardware devices
such as routers, bridges, gateways, firewalls, or switches. General-purpose computers
can also forward packets and perform routing, though they are not specialized
hardware and may suffer from limited performance. The routing process usually directs
forwarding on the basis of routing tables which maintain a record of the routes to various
network destinations. Thus, constructing routing tables, which are held in the router's
memory, is very important for efficient routing. Most routing algorithms use only one
network path at a time. Multipath routing techniques enable the use of multiple
alternative paths. In case of overlapping/equal routes, the following elements are
considered in order to decide which routes get installed into the routing table (sorted
by priority):
1. Prefix-Length: where longer subnet masks are preferred (independent of whether it
is within a routing protocol or over different routing protocol)
2. Metric: where a lower metric/cost is preferred (only valid within one and the same
routing protocol)
3. Administrative distance: where a lower distance is preferred (only valid between
different routing protocols) Routing, in a more narrow sense of the term, is
often contrasted with bridging in its assumption that network addresses are
structured and that similar addresses imply proximity within the network.
Structured addresses allow a single routing table entry to represent the route to
a group of devices. In large networks, structured addressing (routing, in the
narrow sense) outperforms unstructured addressing (bridging). Routing has
become the dominant form of addressing on the Internet. Bridging is still widely
used within localized environments.
(B) FLOODING:
Flooding is a simple routing algorithm in which every incoming packet is sent
through every outgoing link except the one it arrived on Flooding is used in bridging and
in systems such as Usenet and peer-to-peer file sharing and as part of some routing
protocols, including OSPF, DVMRP, and those used in ad-hoc wireless networks.There
are generally two types of flooding available, Uncontrolled Flooding and Controlled
Flooding.Uncontrolled Flooding is the fatal law of flooding. All nodes have neighbours
and route packets indefinitely. More than two neighbours create a broadcast storm.
Controlled Flooding has its own two algorithms to make it reliable, SNCF (Sequence
Number Controlled Flooding) and RPF (Reverse Path Flooding). In SNCF, the node attaches
its own
address and sequence number to the packet, since every node has a memory of addresses
and sequence numbers. If it receives a packet in memory, it drops it immediately while
in RPF, the node will only send the packet forward. If it is received from the next node, it
sends it back to the sender.
Algorithm:
There are several variants of flooding algorithm. Most work roughly as follows:
1. Each node acts as both a transmitter and a receiver.
2. Each node tries to forward every message to every one of its neighbours except the
source node. This results in every message eventually being delivered to all
reachable parts of the network. Algorithms may need to be more complex than
this, since, in some case, precautions have to be taken to avoid wasted duplicate
deliveries and infinite loops, and to allow messages to eventually expire from
the system. A variant of flooding called selective flooding partially addresses these
issues by only sending packets to routers in the same direction. In selective
flooding the routers don't send every incoming packet on every line but only on
those lines which are going approximately in the right direction.

Advantages:
Packet can be delivered, it will (probably multiple times).
Since flooding naturally utilizes every path through the network, it will also use
the shortest path. This algorithm is very simple to implement.
Disadvantage:
Flooding can be costly in terms of wasted bandwidth. While a message may only
have one destination it has to be sent to every host. In the case of a ping flood or a denial
of service attack, it can be harmful to the reliability of a computer network Messages can
become duplicated in the network further increasing the load on the networks
bandwidth as well as requiring an increase in processing complexity to disregard
duplicate messages. Duplicate packets may circulate forever, unless certain precautions
are taken: Use a hop count or a time to live count and include it with each packet. This
value should take into account the number of nodes that a packet may have to
pass through on the way to its destination. Have each node keep track of every packet
seen and only forward each packet once Enforce a network topology without oops
(C) DISTANCE VECTOR ROUTING PROTOCOL USING NS2:
In computer communication theory relating to packet-switched networks, a
distance vector routing protocol is one of the two major classes of routing protocols, the
other major class being the link-state protocol. Distance-vector routing protocols use the
Bellman–Ford algorithm, Ford–Fulkerson algorithm, or DUAL FSM (in the case of Cisco
Systems protocols) to calculate paths.
A distance-vector routing protocol requires that a router informs its neighbours of
topology changes periodically. Compared to link-state protocols, which require a
router to inform all the nodes in a network of topology changes, distance-vector
routing protocols have less computational complexity and message overhead. The term
distance vector refers to the fact that the protocol manipulates vectors (arrays) of
distances to other nodes in the network. The vector distance algorithm was the
original ARPANET routing algorithm and was also used in the internet under the
name of RIP (Routing Information Protocol). Examples of distance-vector routing
protocols include RIPv1 and RIPv2 and IGRP.

Method:
Routers using distance-vector protocol do not have knowledge of the entire
path to a destination. Instead they use two methods:
1. Direction in which router or exit interface a packet should be forwarded.
2. Distance from its destination
Distance-vector protocols are based on calculating the direction and distance to any
link in a network. "Direction" usually means the next hop address and the exit interface.
"Distance" is a measure of the cost to reach a certain node. The least cost route between
any two nodes is the route with minimum distance. Each node maintains a vector (table)
of minimum distance to every node. The cost of reaching a destination is calculated using
various route metrics. RIP uses the hop count of the destination whereas IGRP takes into
account other information such as node delay and available bandwidth. Updates are
performed periodically in a distance-vector protocol where all or part of a router's routing
table is sent to all its neighbors that are configured to use the same distance-vector
routing protocol. RIP supports cross-platform distance vector routing whereas IGRP is a
Cisco Systems proprietary distance vector routing protocol. Once a router has this
information it is able to amend its own routing table to reflect the changes and then
inform its neighbors of the changes. This process has been described as routing by rumor‘
because routers are relying on the information they receive from other routers and
cannot determine if the information is actually valid and true. There are a number of
features which can be used to help with instability and inaccurate routing information.
EGP and BGP are not pure distance-vector routing protocols because a
distance-vector protocol calculates routes based only on link costs whereas in BGP, for
example, the local route preference value takes priority over the link cost.
Count-to-infinity problem:
The Bellman–Ford algorithm does not prevent routing loops from happening and
suffers from the count to infinity problem. The core of the count-to-infinity problem is
that if A tells B that it has a path somewhere, there is no way for B to know if the path
has B as a part of it. To see the problem clearly, imagine a subnet connected like A–B–C–
D–E–F, and let the metric between the routers be "number of jumps". Now suppose that A
is taken offline. In the vector-update-process B notices that the route to A, which was
distance 1, is down – B does not receive the vector update from A. The problem is, B
also gets an update from C, and C is still not aware of the fact that A is down – so it tells B
that A is only two jumps from C (C to B to A), which is false. This slowly propagates through
the network until it reaches infinity (in which case the algorithm corrects itself, due to the
relaxation property of Bellman–Ford).

Sample program:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
setnf [open thro.nam w]
$ns namtrace-all $nf proc finish { }
{global ns nr nf
$ns flush-trace close $nf
close $nr execnamthro.nam& exit 0}
for { set i 0 }
{ $i < 12}
{ incr i 1 }
{set n($i) [$ns node]}
for {set i 0}
{$i < 8}
{incr i}
{$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms
DropTail set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent
$udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0 set udp1 [new Agent/UDP]
$ns attach-agent $n(1)
$udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1 set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto DV
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run
Sample Output:
Link made down:

Result:
Thus the program for creating Simulation of Distance Vector/Link State Routing was
implemented.
EX.NO: 9
PERFORMANCE COMPARISON OF ROUTING PROTOCOLS
Date:

AIM:
To compare various Routing Protocols performance using NS-2

ALGORITHM:
Step 1: Start network simulator OTCL editor.
Step 2: Create new simulator using set ns [new Simulator] syntax
Step 3: Create Trace route to Network Animator
set nf [open out.nam w]
$ns namtrace-all $nf
Step 4: Create procedure to trace all path
proc finish {} {
global ns
$ns flush-trace
puts "running
nam..." exec nam
out.nam &
exit 0
}
Step 4: Connect with UDP and CBR command.
set cbr1 [new Application/Traffic/CBR]
set udp1 [new Agent/UDP]
$cbr1 attach-agent $udp1
$udp1 set dst_ 0x8002
$udp1 set class_ 1
$ns attach-agent $n3 $udp1
Step 5: Setup a new agent for performing Multicast Routing procedure
set rcvr [new Agent/LossMonitor]
#$ns attach-agent $n3 $rcvr
Step 6: Create a group and start services
$ns at 1.2 "$n2 join-group $rcvr 0x8002"
$ns at 1.25 "$n2 leave-group $rcvr 0x8002"
$ns at 1.3 "$n2 join-group $rcvr 0x8002"
$ns at 1.35 "$n2 join-group $rcvr 0x8001"
$ns at 1.0 "$cbr0 start"
$ns at 1.1 "$cbr1 start"
$ns at 2.0 "finish"
Step 7: Run and Execute the
program.
$ns run
PROGRAM:
set ns [new Simulator]
$ns multicast set f [open out.tr w]
$ns trace-all $f
$ns namtrace-all [open out.nam w]
$ns color 1 red
# prune/graft packets
$ns color 30 purple
$ns color 31 green set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node]
# Use automatic layout
$ns duplex-link $n0 $n1 1.5Mb 10ms DropTail
$ns duplex-link $n1 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n1 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n1 $n3 orient right-down
$ns duplex-link-op $n0 $n1 queuePos 0.5
set mrthandle [$ns mrtproto DM {}]
set cbr0 [new Application/Traffic/CBR]
set udp0 [new Agent/UDP]
$cbr0 attach-agent $udp0
$ns attach-agent $n1 $udp0
$udp0 set dst_ 0x8001
set cbr1 [new Application/Traffic/CBR]
set udp1 [new Agent/UDP]
$cbr1 attach-agent $udp1
$udp1 set dst_ 0x8002
$udp1 set class_ 1
$ns attach-agent $n3 $udp1
set rcvr [new Agent/LossMonitor]
#$ns attach-agent $n3 $rcvr
$ns at 1.2 "$n2 join-group $rcvr 0x8002"
$ns at 1.25 "$n2 leave-group $rcvr 0x8002"
$ns at 1.3 "$n2 join-group $rcvr 0x8002"
$ns at 1.35 "$n2 join-group $rcvr 0x8001"
$ns at 1.0 "$cbr0 start"
$ns at 1.1 "$cbr1 start"
$ns at 2.0 "finish" proc finish {} {
global ns
$ns flush-trace
puts "running nam..."
exec nam
out.nam & exit 0
}
$ns run
Result:
Thus the Routing Protocols performance compared by using NS-2 and output
verified by using Network Animator.
EX.NO: 10
Simulation of Error Correction Code(CRC)
Date:

AIM:
To Simulation of Error Correction Code using NS2.

Procedure:

Cyclic redundancy checks (CRC):

CRC or Cyclic Redundancy Check — it is a method of detecting random changes / errors in the
communication channel.
CRC uses a generator polynomial that is available on both the sender and receiver sides. An
example generator polynomial looks like x ^ 3 + 1. This generator polynomial represents the
key 1001. Another example — x ^ 2 + x. this represents key 110.

Example:
Let the data be sent "EVN"
We are converting the string to binary string data.
input_string="EVN" # CONVERT string data to binary string data

data=(’ ’.join(format(ord (x),’b’)for x in input_string))


print(data)

OUTPUT: 100010110101101001110

CRC Key: 10 01
Code: CRC Key Length -1 - & gt; 000 appended at the end of the data.
New data: 100010110101101001110000 Key: 1001

ALGORITHM:

Sender side
1. The task is to send the string data to the server / recipient side.
2. The sender sends a string, say "EVN".
3. First, this string is converted to a binary string. The key "100010110101101001110" is
known to both the sender and the recipient, here the key is 1001.
4. This data is encoded using a CRC code using a client / sender key.
5. This encoded data is sent to the recipient.
6. The receiver later decodes the encoded data string to check if there was any error or not.

Receiver side
1. The receiver receives the encoded data string from the sender.
2. The receiver decodes the data using the key and finds out the remainder.
3. If the remainder is zero, it means that there are no errors in the data sent by the sender to
the recipient.
4. If the remainder turns out to be non-zero, it means that an error has occurred, a negative
acknowledgment is sent to the sender. The sender then resends the data until the receiver
receives the correct data.
Example:

Client

CRC10A.py

# Import socket module

import socket

def xor(a,b):

# initialize result

result=[]

# Traverse all bits, if bits are

# same, then XOR is 0, else 1

for i in range(1,len(b)):

if a[i]==b[i]:

result.append('0')
else:

result.append('1')

return ''.join(result)

# Performs Modulo-2 division

def mod2div(divident, divisor):

# Number of bits to be XORed at a time.

pick=len(divisor)

# Slicing the divident to appropriate

# length for particular step

tmp=divident[0:pick]

while pick<len(divident):

if tmp[0]=='1':

# replace the divident by the result

# of XOR and pull 1 bit down

tmp = xor(divisor, tmp) + divident[pick]

else: # If leftmost bit is ’0’

# If the leftmost bit of the dividend (or the

# part used in each step) is 0, the step cannot

# use the regular divisor; we need to use an

# all-0s divisor.

tmp=xor('0'*pick,tmp)+divident[pick]

# increment pick to move further

pick+=1

# For the last n bits, we have to carry it out

# normally as increased value of pick will cause

# Index Out of Bounds.

if tmp[0]=='1':

tmp=xor(divisor,tmp)

else:
tmp=xor('0'*pick,tmp)

checkword=tmp

return checkword

# Function used at the sender side to encode

# data by appending remainder of modular division

# at the end of data.

def encodeData(data,key):

l_key=len(key)

# Appends n-1 zeroes at end of data

appended_data=data +'0'*(l_key-1)

remainder=mod2div(appended_data,key)

# Append remainder in the original data

codeword = data + remainder

return codeword

# Create a socket object

s=socket.socket()

# Define the port on which you want to connect

port=12345

# connect to the server on local computer

s.connect(('127.0.0.1',port))

# Send data to server ’Hello world’

## s.sendall(’Hello World’)

input_string=input("Enter data you want to send->")

#s.sendall(input_string)

data=(''.join(format(ord(x),'b') for x in input_string))

print("Entered data in binary format :",data)

key="1001"

ans=encodeData(data,key)
print("Encoded data to be sent to server in binary format :",ans)

s.sendto(ans.encode(),('127.0.0.1', 12345))

# receive data from the server

print("Received feedback from server :",s.recv(1024).decode())

# close the connection

s.close()

Server

crc10b.py

# First of all import the socket library

import socket

def xor(a,b):

# initialize result

result=[]

# Traverse all bits, if bits are

# same, then XOR is 0, else 1

for i in range(1,len(b)):

if a[i]==b[i]:

result.append('0')

else:

result.append('1')

return ''.join(result)

# Performs Modulo-2 division

def mod2div(divident,divisor):

# Number of bits to be XORed at a time.

pick=len(divisor)

# Slicing the divident to appropriate


# length for particular step

tmp=divident[0:pick]

while pick<len(divident):

if tmp[0]=='1':

# replace the divident by the result

# of XOR and pull 1 bit down

tmp=xor(divisor,tmp)+divident[pick]

else: # If leftmost bit is ’0’

# If the leftmost bit of the dividend (or the

# part used in each step) is 0, the step cannot

# use the regular divisor; we need to use an

# all-0s divisor.

tmp=xor('0'*pick,tmp)+divident[pick]

# increment pick to move further

pick+=1

# For the last n bits, we have to carry it out

# normally as increased value of pick will cause

# Index Out of Bounds.

if tmp[0]=='1':

tmp=xor(divisor,tmp)

else:

tmp=xor('0'*pick,tmp)

checkword=tmp

return checkword

# Function used at the receiver side to decode

# data received by sender

def decodeData(data, key):


l_key=len(key)

# Appends n-1 zeroes at end of data

appended_data=data.decode()+'0'*(l_key-1)

remainder=mod2div(appended_data,key)

return remainder

# Creating Socket

s=socket.socket()

print("Socket successfully created")

# reserve a port on your computer in our

# case it is 12345 but it can be anything

port=12345

s.bind(('',port))

print("socket binded to %s"%(port))

# put the socket into listening mode

s.listen(5)

print("socket is listening")

while True:

# Establish connection with client.

c,addr=s.accept()

print('Got connection from',addr)

# Get data from client

data=c.recv(1024)

print("Received encoded data in binary format :",data.decode())

if not data:

break

key="1001"

ans = decodeData(data,key)

print("Remainder after decoding is->"+ans)

# If remainder is all zeros then no error occured


temp="0"*(len(key)-1)

if ans==temp:

c.sendto(("THANK you Data ->"+data.decode()+" Received No error


FOUND").encode(),('127.0.0.1',12345))

else:

c.sendto(("Error in data").encode(),('127.0.0.1',12345))

c.close()

OUTPUT

Server

novice@novice:~$ python3 crc10b.py

Socket successfully created

socket binded to 12345

socket is listening

Got connection from ('127.0.0.1', 50576)

Received encoded data in binary format : 100010110101101001110111

Remainder after decoding is->000

ClIent

novice@novice:~$ python3 CRC10A.py

Enter data you want to send->EVN

Entered data in binary format : 100010110101101001110

Encoded data to be sent to server in binary format : 100010110101101001110111

Received feedback from server : THANK you Data -


>100010110101101001110111 Received No error FOUND
Result:
Thus the Simulation of Error Correction Code(CRC) implemented.

You might also like