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

Computer Networks

The document outlines various network commands and their uses including: 1. Commands like ifconfig, netstat, ping, arp, telnet, ftp, finger, traceroute, and whois are used to understand and configure network interfaces, view network connections and statistics, test connectivity, lookup domain information, and more. 2. Socket programming is covered for implementing connection-oriented and connection-less services using standard and user-defined ports. 3. Additional programs described include remote command execution, DNS configuration, routing protocol configuration, error detection codes, message queues, congestion control, and more.

Uploaded by

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

Computer Networks

The document outlines various network commands and their uses including: 1. Commands like ifconfig, netstat, ping, arp, telnet, ftp, finger, traceroute, and whois are used to understand and configure network interfaces, view network connections and statistics, test connectivity, lookup domain information, and more. 2. Socket programming is covered for implementing connection-oriented and connection-less services using standard and user-defined ports. 3. Additional programs described include remote command execution, DNS configuration, routing protocol configuration, error detection codes, message queues, congestion control, and more.

Uploaded by

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

Programs

Understanding and using of commands like ifconfig, ftp, finger,


1.
traceroute, whois

2. Understanding and using of commands like netstat, ping, arp, telnet.

Implementation of study of Network IP


3.

4. Socket Programming: Implementation of Connection-Oriented Service using


standard ports.
5. Implementation of Connection-Less Service using standard ports

6. Implementation of Connection-Oriented Iterative Echo-Server, date and time,


character generation using user-defined ports
Implementation of Connectionless Iterative Echo-server, date and time,
7.
character generation using user-defined ports.

8. Implementation of Connection-Oriented Concurrent Echo-server, date and


time, character generation using user-defined ports
Program for connection-oriented Iterative Service in which server reverses the
9.
string sent by the client and sends it back

10. Program for connection-oriented Iterative service in which server changes


the case of the strings sent by the client and sends back (Case Server).
11. Program for Connection-Oriented Iterative service in which server calculates
the Net-salary of an Employee based on the following details sent by the
12. Program for file access using sockets.

13. Program for Remote Command Execution using sockets

14. Implementation of DNS

15.
Configure a network using Distance vector Routing protocol.

16. Configure a network using Link state vector Routing protocol.

17.
Write a program for error detecting code using CRC-CCITT (16-bits).

18.
Implement the program using as message queues or FIFO as IPC channels.

19
Write a program for congestion control using Leaky bucket algorithm.

20
Write a program for Hamming code
21
Implementation of Connection-Oriented Iterative Echo-Server.
22
Implementation of Connectionless Iterative Echo-server.

23
Implement Connection of computers in Local Area Network.

24
Implementation of Connectionless date and time.

25
Program for Connection-Concurrent Iterative service in which server calculates
the net salary ofan employee based on the following details sent by the client. i)
basic ii) hra iii) da iv) net- salary=basic+ hra+ da- pt- epf.

26
Program for Connection-less Iterative service in which server calculates the net
salary of anemployee based on the following details sent by the client. i) basic ii)
hra iii) da iv) net- salary=basic+ hra+ da- pt- epf.
27
Write a program for error detecting code using CRC-CCITT (8-bits).

28
Implementation of student grade server.
29
Write a program for distance vector algorithm to find suitable path for
transmission.

30
Implementation of authentication server
Program 1: Understanding and using of commands like ifconfig,
netstst, ping, arp, telnet, ftp, finger, traceroute, whois etc

IFCONFIG
The Unix command ifconfig (short for interface configurator) serves to configure and control TCP/IP network
interfaces from a command line interface (CLI).
Common uses for ifconfig include setting an interface's IP address and netmask, and disabling or enabling a given
interface.
Ipconfig is an MS-DOS utility that can be used from MS-DOS and an MS-DOS shell to display the network settings
currently assigned and given by a network. This command can be utilized to verify a network connection as well as
to verify your network settings.
Syntax: ipconfig [/allcompartments] [/? | /all | /renew [adapter] | /release [adapter] | /renew6 [adapter] | /release6
[adapter] | /flushdns | /displaydns | /registerdns | /showclassid adapter | /setclassid adapter [classid] | /showclassid6
adapter | /setclassid6 adapter [classid] ]
Example:ipconfig/all
Output:

FTP
File Transfer Protocol (FTP): FTP is a network protocol used to transfer data from one computer to another
through a network such as the Internet.FTP is a file transfer protocol for exchanging and manipulating files over a
TCP computer network. An FTP client may connect to an FTP server to manipulate files on that server.FTP runs
over TCP. It defaults to listen on port 21 for incoming connections from FTP clients. A connection to this port from
the FTP Client forms the control stream on which commands are passed from the FTP client to the FTP server and
on occasion from the FTP server to the FTP client. FTP uses out-of-band control, which means it uses a separate
connection for control and data. Thus, for the actual file transfer to take place, a different connection is required
which is called the data stream.
Syntax: ftp [-46pinegvd] [host [port]]
Example: ftp exampleftp.computerhope.com
Output:
FINGER
In computer networking, the Name/Finger protocol and the Finger user information protocol are simple network
protocols for the exchange of human-oriented status and user information. finger looks up and displays information
about system users.
Syntax: finger [-lmsp] [user ...] [user@host ...]
Example: finger -p ch
Output:
TRACEROUTE
traceroute is a computer network tool used to determine the route taken by packets across an IP network . An IPv6
variant, traceroute6, is also widely available.Traceroute is often used for network troubleshooting. By showing a list
of routers traversed, it allows the user to identify the path taken to reach a particular destination on the network. This
can help identify routing problems or firewalls that may be blocking access to a site. Traceroute is also used by
penetration testers to gather information about network infrastructure and IP ranges around a given host. It can also
be used when downloading data, and if there are multiple mirrors available for the same piece of data, one can trace
each mirror to get a good idea of which mirror would be the fastest to use.
Syntax: traceroute [-46dFITUnreAV] [-f first_ttl] [-g gate,...] [-i device]
[-m max_ttl] [-p port] [-s src_addr] [-q nqueries]
[-N squeries] [-t tos] [-l flow_label] [-w waittime]
[-z sendwait] [-UL] [-D] [-P proto] [--sport=port] [-M method]
[-O mod_options] [--mtu] [--back] host [packet_len]
Example: traceroute www.google.com
Output:
WHO IS
WHOIS (pronounced "who is"; not an acronym) is a query/response protocol which is widely used for querying an
official database in order to determine the owner of a domain name, an IP address, or an autonomous system number
on the Internet. WHOIS lookups were traditionally made using a command line interface, but a number of simplified
web-based tools now exist for looking up domain ownership details from different databases. WHOIS normally runs
on TCP port 43.
The WHOIS system originated as a method that system administrators could use to look up information to contact
other IP address or domain name administrators (almost like a "white pages").
Syntax: whois [ -h HOST ] [ -p PORT ] [ -aCFHlLMmrRSVx ] [ -g SOURCE:FIRST-LAST ] [ -i ATTR ] [ -S
SOURCE][-TTYPE]object
Example:whoiswww.google.com
Output:

2
Program 2: Understanding and using of commands like netstst, ping,
arp, telnet.

NETSTAT
netstat (network statistics) is a command-line tool that displays network connections (both incoming and outgoing),
routing tables, and a number of network interface statistics.
It is used for finding problems in the network and to determine the amount of traffic on the network as a
performance measurement.
Parameters
Parameters used with this command must be prefixed with a hyphen (-) rather than a slash (/).
-a : Displays all active TCP connections and the TCP and UDP ports on which the computer is listening.
-e : Displays ethernet statistics, such as the number of bytes and packets sent and received. This parameter can be
combined with -s.
-f : Displays fully qualified domain names for foreign addresses.
-i : Displays network interfaces and their statistics (not available under Windows)
-n : Displays active TCP connections, however, addresses and port numbers are expressed numerically and no
attempt is made to determine names.
-o : Displays active TCP connections and includes the process ID (PID) for each connection.
-p Linux: Process : Show which processes are using which sockets
Syntax: NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-x] [-t] [interval]
Output:

3
PING
Ping is a computer network tool used to test whether a particular host is reachable across an IP network; it is also
used to self test the network interface card of the computer, or as a speed test. It works by sending ICMP “echo
request” packets to the target host and listening for ICMP “echo response” replies. Ping does not estimate the round-
trip time, as it does not factor in the user's connection speed, but instead is used to record any packet loss, and print a
statistical summary when finished.
The word ping is also frequently used as a verb or noun, where it is usually incorrectly used to refer to the round-trip
time, or measuring the round-trip time.
Syntax: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS] [-r count] [-s count] [[-j host-list] | [-k host-list]] [-w
timeout][-R][-Ssrcaddr][-4][-6target_name]

Output:

4
ARP
In computer networking, the Address Resolution Protocol (ARP) is the method for finding a host's link layer
(hardware) address when only its Internet Layer (IP) or some other Network Layer address is known.
ARP has been implemented in many types of networks; it is not an IP-only or Ethernet-only protocol. It can be used
to resolve many different network layer protocol addresses to interface hardware addresses, although, due to the
overwhelming prevalence of IPv4 and Ethernet, ARP is primarily used to translate IP addresses to Ethernet MAC
addresses.
Arp syntax:
ARP -s inet_addr eth_adr [if_addr]
ARP -d inet_addr [if_addr]
ARP -a [inet_addr] [-N if_addr]
Example: arp -a
Output:

5
TELNET
Telnet (Telecommunication network) is a network protocol used on the Internet or local area network (LAN)
connections.
Typically, telnet provides access to a command-line interface on a remote machine.
The term telnet also refers to software which implements the client part of the protocol. Telnet clients are available
for virtually all platforms
Protocol details: Telnet is a client-server protocol, based on a reliable connection-oriented transport. Typically this
protocol is used to establish a connection to TCP port 23
Syntax: telnet [-468ELadr] [-S tos] [-b address] [-e escapechar] [-l user] [-n tracefile] [host [port]]
Example: telnet myhost.com
Output:

6
Program 3: Study of network IP

import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)

print("Your Computer Name is:" + hostname)


print("Your Computer IP Address is:" + IPAddr)

Output:
Your Computer Name is:emscripten
Your Computer IP Address is:172.29.1.0

7
Program 4: Socket Programming: Implementation of Connection-Oriented
Service using standard ports.

Server.py

#!/usr/bin/python # This is server.py file


import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection

Client.py

#!/usr/bin/python # This is client.py file


import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close() # Close the socket when done

Output:

# Following would start a server in background.


$ python server.py

# Once server is started run client as follows:


$ python client.py

Got connection from (172.29.1.0)


Thank you for connecting.

8
Program 5: Implementation of Connection-Less Service using standard ports

Server.py

import socket
host = "127.0.0.1"
port = 5001
server = socket.socket()
server.bind((host,port))
server.listen()
conn, addr = server.accept()
print ("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if not data:
break
print ("from connected user: " + str(data))
data = str(data).upper()
print ("Received from User: " + str(data))
data = input("type message: ")
conn.send(data.encode())
conn.close()

9
Client.py
import socket
host = '127.0.0.1'
port = 5001
obj = socket.socket()
obj.connect((host,port))
message = input("type message: ")
while message != 'q':
obj.send(message.encode())
data = obj.recv(1024).decode()
print ('Received from server: ' + data)
message = input("type message: ")
obj.close()
Output:

10
Program 6: Implementation of Connection-Oriented Iterative Echo-Server,
date and time, character generation using user-defined ports
server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()

client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()
11
print("The time got from the server is %s" % tm.decode('ascii'))

Output:

$ python server.py
Got a connection from (172.29.1.0)
$ python client.py
The time got from the server is Tue Feb 20 21:17:15 2022

12
Program 7: Implementation of Connectionless Iterative Echo-server, date and
time, character generation using user-defined ports.
Server.py
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
sock.bind(server_address)
while True:
print ('waiting to receive message')
data, address = sock.recvfrom(4096)
msg=data.decode()
print(msg)
if data:
sent = sock.sendto(data, address)

Client.py
import socket
from datetime import datetime
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
message = 'This is the message. It will be repeated.'
try:
sent = sock.sendto(bytes(message, 'utf-8'), server_address)
data, server = sock.recvfrom(4096)
msg=data.decode()
time=datetime.now().strftime('%X')
print(f'Received echo: {msg} at {time}')
finally:
print ('closing socket')
sock.close()

output:
$ python server.py
Got a connection from ('localhost', 10000)
$ python client.py
The time got from the server is Wed Feb20 21:17:15 2022

13
Program 8: Implementation of Connection-Oriented Concurrent Echo-server,
date and time, character generation using user-defined ports

server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 1948
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()

14
client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 1948
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" % tm.decode('ascii'))

Output:

$ python server.py
Got a connection from (172.29.1.0)
$ python client.py
The time got from the server is Tue Feb 20 19:14:15 2022

15
Program 9: Program for connection-oriented Iterative Service in which server
reverses the string sent by the client and sends it back

Server.py

import socket
host=socket.gethostname()
port=1234
server_socket=socket.socket()
server_socket.bind((host,port))
server_socket.listen()
print('SERVER IS RUNNING')
conn,addr=server_socket.accept()
print(f'Connected to {str(addr)}')
while True:
data=conn.recv(1024).decode()
if data=='bye':
break
list=data.split()
back_string=' '.join(reversed(list))
print('Replied with reverse')
conn.send(back_string.encode())
print('SERVER STOPPED')
conn.close()

Client.py
import socket
host=socket.gethostname()
port=1234
client_socket=socket.socket()

client_socket.connect((host, port))

message=input('Say what to the server?')

while message.lower().strip()!='hi':
message=input('Send to server: ')
client_socket.send(message.encode())
if (message == 'hi'):
break
message=client_socket.recv(1024).decode()
print(f'Server replied: {message}')

print('Client disconnected')
client_socket.close()

16
Output:

# Following would start a server in background.


$ python server.py

SERVER IS RUNNING
Connected to'172.29.1.0
'BALNC
Replied with reverse
SERVER STOPPED
# Once server is started run client as follows:
$ python client.py

Say what to the server? CNLAB

hi

17
Program 10: Program for connection-oriented Iterative service in which server
changes the case of the strings sent by the client and sends back (Case Server).
Server.py
import socket
host=socket.gethostname()
port=1233
server_socket=socket.socket()
server_socket.bind((host,port))
server_socket.listen()
print('SERVER HAS STARTED AND LISTENING')
conn, addr=server_socket.accept()
print(f'Connected established with {str(addr)}')
while(True):
reversed_message = ''
message=conn.recv(1024).decode()
if message=='bye':
break
for char in message:
if (char.isupper()):
reversed_message += char.lower()
else:
reversed_message += char.upper()
print('Reverse-cased string returned to client')
conn.send(reversed_message.encode())
print('STOPPING SERVER')
conn.close()

Client.py
import socket
host=socket.gethostname()
port=1233
client_socket=socket.socket()
client_socket.connect((host,port))
print('CONNECTED TO SERVER')
while(True):
message=input('Send what to the server?')
client_socket.send(message.encode())
if (message == 'bye'):
break
message=client_socket.recv(1024).decode()
print(f'Reversed string: {message}')
print('DISCONNECTING CLIENT')
client_socket.close()

18
Output:

# Following would start a server in background.


$ python server.py
SERVER HAS STARTED AND LISTENING'
Connected established with
'172.29.1.0' Reverse-cased string
returned to client' STOPPING
SERVER

# Once server is started run client as follows:


$ python client.py
CONNECTED TO SERVER'
'Send what to the server?' HEllo
Reversed string:hello
Bye
DISCONNECTING CLIENT'

19
Program 11: Program for Connection-Oriented Iterative service in which
server calculates the Net-salary of an Employee based on the following details
sent by the client
i) basic-sal ii) hra iii) da iv) pt v) epf ( net-sala=basic+hra+da-pt-epf)
Server.py

import socket
host=socket.gethostname()
port=1234
server_socket=socket.socket()
server_socket.bind((host,port))
server_socket.listen()
print('SERVER STARTED')
conn, addr=server_socket.accept()
print(f'CONNECTED TO CLIENT: {str(addr)}')
basic_salary=int(conn.recv(1024).decode())
house_rent_allowance=int(conn.recv(1024).decode())
transport_allowance=int(conn.recv(1024).decode())
FBP_allowance=int(conn.recv(1024).decode())
statutory_bonus=int(conn.recv(1024).decode())
income_tax=int(conn.recv(1024).decode())
provident_fund=int(conn.recv(1024).decode())
net_salary=(basic_salary+house_rent_allowance+transport_allowance+FBP_allowance+statutory_bonus)-
(income_tax+provident_fund)
conn.send(str(net_salary).encode())
print(f'Replied with calculation{net_salary}')
print('CLOSING SERVER')

20
Client.py
import socket
host=socket.gethostname()
port=1234
client_socket=socket.socket()
client_socket.connect((host,port))
message=input('Basic salary:')
client_socket.send(message.encode())
message=input('House rent allowance:')
client_socket.send(message.encode())
message=input('Transport allowance:')
client_socket.send(message.encode())
message=input('FBP allowance:')
client_socket.send(message.encode())
message=input('Statutory bonus:')
client_socket.send(message.encode())
message=input('Income tax:')
client_socket.send(message.encode())
message=input('Provident fund:')
client_socket.send(message.encode())
net_salary=int(client_socket.recv(1024).decode())
print(f'Calculated net salary: {net_salary}')
print('DISCONNECTING CLIENT')
client_socket.close()

Output:

# Following would start a server in background.


$ python server.py
SERVER STARTED '
CONNECTED TO CLIENT: ''
'Replied with calculation 46600
CLOSING SERVER

# Once server is started run client as follows:


$ python client.py
Basic Salary 40000
House Rent Allowance 5000
Transport Allowance 1000
Fbp Allowance 500
Statuary bonus 700
Income tax 100
Provident fund 500
Calculated net salary:46600
DISCONNECTING CLIENT

21
Program 12: Program for file access using sockets.
Server.py
import socket
import sys
s = socket.socket()
s.bind(("localhost",9999))
s.listen(10) # Accepts up to 10 incoming connections..
sc, address = s.accept()
print address
i=1
f = open('file_'+ str(i)+".pdf",'wb') # Open in binary
i=i+1
while (True):
# We receive and write to the file.
l = sc.recv(1024)
while (l):
f.write(l)
l = sc.recv(1024)
f.close()
sc.close()
s.close()

Client.py

import socket
import sys
s = socket.socket()
s.connect(("localhost",9999))
f = open ("libroR.pdf", "rb")
l = f.read(1024)
while (l):
s.send(l)
l = f.read(1024)
s.close()

Output:
$ python Server.py – '172.29.1.0
$ python Client.py - “welcome to Aurora”

22
Program 13: Program for Remote Command Execution using sockets

Server.py
import sys, socket
#socket.setdefaulttimeout(150)
host = 127.0.0.1
port = 50103
BUFSIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: %s"%port)
s.listen(1)
print("Now listening...\n")
#conn = client socket
conn, addr = s.accept()
while True:
print 'New connection from %s:%d' % (addr[0], addr[1])
data = conn.recv(BUFSIZE)
if not data:
break
elif data == 'exit':
conn.send('\0')
else:
conn.send(data)
def quit(connection):
connection.close()

23
Client.py
import sys
import socket
BUFSIZE = 1024
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect(('localhost', 50103))
while True:
cmd = raw_input('Enter a command: ')
conn.send(cmd)
data = conn.recv(BUFSIZE)
msglen = len(data)
print "got: %s" % data
print "received: %d" % msglen
if data == '\0':
print 'exiting...'
sys.exit(0)

Output:

Enter a command: ls
got: ls
received: 2

24
Program 14: Implementation of DNS
import dnspython as dns
import dns.resolver

result = dns.resolver.query('aurora.edu', 'A')


for ipval in result:
print('IP', ipval.to_text())

Output:

('IP', u'192.168.1.13)

25
Program 15: Configure a network using Distance vector Routing protocol.

from collections import defaultdict


class Network:
def init (self, nodes):
self.nodes = nodes
self.routing_table = defaultdict(dict)

def add_link(self, node1, node2, cost):


self.routing_table[node1][node2] = cost
self.routing_table[node2][node1] = cost

def bellman_ford(self):
for node in self.nodes:
self.routing_table[node][node] = 0

for _ in range(len(self.nodes) - 1):


for src in self.nodes:
for dest in self.nodes:
for via in self.nodes:
if src != dest and src != via and dest != via:
if via in self.routing_table[src] and dest in self.routing_table[via]:
cost = self.routing_table[src][via] + self.routing_table[via][dest]
if dest not in self.routing_table[src] or cost < self.routing_table[src][dest]:
self.routing_table[src][dest] = cost

def print_routing_table(self):
for node in self.nodes:
print(f"Routing table for node {node}:")
for dest, cost in self.routing_table[node].items():
print(f" {dest}: {cost}")

if name == " main ":


nodes = ['A', 'B', 'C', 'D', 'E']
network = Network(nodes)
network.add_link('A', 'B', 5)
network.add_link('A', 'C', 3)
network.add_link('B', 'C', 2)
network.add_link('B', 'D', 4)
network.add_link('C', 'D', 6)
network.add_link('C', 'E', 6)
network.add_link('D', 'E', 3)
network.bellman_ford()
network.print_routing_table()

output:
Routing table for node A:
A: 0
B: 5
C: 3
D: 9
E: 12
26
Routing table for node B:
A: 5
B: 0
C: 2
D: 4
E: 7
Routing table for node C:
A: 3
B: 2
C: 0
D: 6
E: 9
Routing table for node D:
A: 9
B: 4
C: 6
D: 0
E: 3
Routing table for node E:
A: 12
B: 7
C: 9
D: 3
E: 0

27
Program 16: Configure a network using Link state vector Routing protocol.
from collections import defaultdict
import heapq
class Network:
def init (self, nodes):
self.nodes = nodes
self.routing_table = defaultdict(dict)
self.topology = defaultdict(dict)

def add_link(self, node1, node2, cost):


self.topology[node1][node2] = cost
self.topology[node2][node1] = cost

def dijkstra(self, src):


heap = [(0, src)]
visited = set()
while heap:
(cost, curr) = heapq.heappop(heap)
if curr in visited:
continue
visited.add(curr)
self.routing_table[src][curr] = cost
for neighbor, link_cost in self.topology[curr].items():
if neighbor not in visited:
heapq.heappush(heap, (cost + link_cost, neighbor))

def link_state_routing(self):
for node in self.nodes:
self.dijkstra(node)

def print_routing_table(self):
for node in self.nodes:
print(f"Routing table for node {node}:")
for dest, cost in self.routing_table[node].items():
print(f" {dest}: {cost}")

if name == " main ":


nodes = ['A', 'B', 'C', 'D', 'E']
network = Network(nodes)
network.add_link('A', 'B', 5)
network.add_link('A', 'C', 3)
network.add_link('B', 'C', 2)
network.add_link('B', 'D', 4)
network.add_link('C', 'D', 6)
network.add_link('C', 'E', 6)
network.add_link('D', 'E', 3)
network.link_state_routing()
network.print_routing_table()

output:
Routing table for node A:
A: 0
B: 5

28
C: 3
D: 9
E: 12
Routing table for node B:
A: 5
B: 0
C: 2
D: 4
E: 7
Routing table for node C:
A: 3
B: 2
C: 0
D: 6
E: 9
Routing table for node D:
A: 9
B: 4
C: 6
D: 0
E: 3
Routing table for node E:
A: 12
B: 7
C: 9
D: 3
E: 0

29
Program 17: Write a program for error detecting code using CRC-CCITT (16-bits).

def crc_ccitt(data):
"""
Computes the 16-bit CRC-CCITT checksum of the input data.
"""
# The CRC-CCITT polynomial is x^16 + x^12 + x^5 + 1 (0x1021).
crc = 0xFFFF

for byte in data:


crc ^= (byte << 8)
for _ in range(8):
if crc & 0x8000:
crc = (crc << 1) ^ 0x1021
else:
crc <<= 1
return crc & 0xFFFF
if name == " main ":
# Example usage:
data = b"Hi, world!"
checksum = crc_ccitt(data)
print(f"Data: {data}")
print(f"CRC-CCITT checksum: {checksum:04X}")

Output:
Data: b'Hi, world!'
CRC-CCITT checksum: 0x2EF4

30
Program 18: Implement the program using as message queues or FIFO as IPC channels.

import multiprocessing
import time

def sender(queue):
"""
Sends messages to the receiver process via the message queue.
"""
messages = ["Hi", "Iam", "From", "Aurora"]for
msg in messages:
queue.put(msg)
print(f"Sent message: {msg}")
time.sleep(1)
def receiver(queue):
"""
Receives messages from the sender process via the message queue.
"""
while True:
msg = queue.get()
print(f"Received message: {msg}")
if msg == "quit":
break
if name__ == " main ":
queue = multiprocessing.Queue()
p1 = multiprocessing.Process(target=sender, args=(queue,))
p2 = multiprocessing.Process(target=receiver, args=(queue,))
p1.start()
p2.start()
p1.join()
p2.join()

31
Output:
Sent message: Hi
Received message: Hi
Sent message: Iam
Receivedmessage:Iam

Sent message: From


Received message: From
Sent message: Aurora
Received message:Aurora

32
Program 19:Write a program for congestion control using Leaky bucket algorithm.
#initial packets in the bucket
storage = 0

# total no. of times bucket content is checked


no_of_queries = 4

# total no. of packets that can


# be accommodated in the bucket
bucket_size = 10

# no. of packets that enters the bucket at a time


input_pkt_size = 6

# no. of packets that exits the bucket at a time


output_pkt_size = 1
for i in range(0, no_of_queries): # space left

size_left = bucket_size - storage


if input_pkt_size <= size_left:
# update storage
storage += input_pkt_size
else:
print("Packet loss = ", input_pkt_size)

print(f"Buffer size= {storage} out of bucket size = {bucket_size}")

# as packets are sent out into the network, the size of the storage decreases
storage -= output_pkt_size

Output

Buffer size= 4 out of bucket size= 10


Buffer size= 7 out of bucket size= 10
Buffer size= 10 out of bucket size= 10
Packet loss = 6
Buffer size= 9 out of bucket size= 10

33
Program 20:Write a program for Hamming code
def calcRedundantBits(m):

# Use the formula 2 ^ r >= m + r + 1


# to calculate the no of redundant bits.
# Iterate over 0 .. m and return the value
# that satisfies the equation

for i in range(m):
if(2**i >= m + i + 1):
return i
def posRedundantBits(data, r):
# Redundancy bits are placed at the positions
# which correspond to the power of 2.
j=0
k=1
m = len(data)
res = ''
# If position is power of 2 then insert '0'
# Else append the data
for i in range(1, m + r+1):
if(i == 2**j):
res = res + '0'
j += 1
else:
res = res + data[-1 * k]
k += 1
# The result is reversed since positions are
# counted backwards. (m + r+1 ... 1)
return res[::-1]
def calcParityBits(arr, r):
n = len(arr)
# For finding rth parity bit, iterate over
# 0 to r - 1
for i in range(r):
val = 0
for j in range(1, n + 1):
# If position has 1 in ith significant
# position then Bitwise OR the array value
# to find parity bit value.
if(j & (2**i) == (2**i)):
val = val ^ int(arr[-1 * j])
# -1 * j is given since array is reversed
# String Concatenation
# (0 to n - 2^r) + parity bit + (n - 2^r + 1 to n)
arr = arr[:n-(2**i)] + str(val) + arr[n-(2**i)+1:]
return arr

def detectError(arr, nr):


n = len(arr)
res = 0

# Calculate parity bits again

34
for i in range(nr):
val = 0
for j in range(1, n + 1):
if(j & (2**i) == (2**i)):
val = val ^ int(arr[-1 * j])

# Create a binary no by appending


# parity bits together.
res = res + val*(10**i)
# Convert binary to decimal
return int(str(res), 2)
# Enter the data to be transmitted
data = '1011001'
# Calculate the no of Redundant Bits Required
m = len(data)
r = calcRedundantBits(m)
# Determine the positions of Redundant Bits
arr = posRedundantBits(data, r)
# Determine the parity bits
arr = calcParityBits(arr, r)
# Data to be transferred
print("Data transferred is " + arr)
# Stimulate error in transmission by changing
# a bit value.
# 10101001110 -> 11101001110, error in 10th position.
arr = '11101001110'
print("Error Data is " + arr)
correction = detectError(arr, r)
if(correction==0):
print("There is no error in the received message.")
else:
print("The position of error is ",len(arr)-correction+1,"from the left")

Output
Data transferred is 10101001110
Error Data is 11101001110
The position of error is 2 from the left

35
Program 21: Implementation of Connection-Oriented Iterative Echo-Server.
server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentmsg =
“HelloWorld”+"\r\n"
clientsocket.send(currentmsg.encode('ascii'))
clientsocket.close()
client.py

import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()

36
print("The time got from the server is %s" % tm.decode('ascii'))

37
Output:
$ python server.py
Got a connection from (192.168.1.13)
$ python client.py
The time got from the server is HelloWorld

38
Program 22: Implementation of Connectionless Iterative Echo-server.

Server.py
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
sock.bind(server_address)
while True:
print ('waiting to receive message')
data, address = sock.recvfrom(4096)
msg=data.decode()
print(msg)
if data:
sent = sock.sendto(data, address)

Client.py
import socket
from datetime import datetime
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
message = 'This is the message. It will be repeated.'
try:
sent = sock.sendto(bytes(message, 'utf-8'), server_address)
data, server = sock.recvfrom(4096)
msg=data.decode()
time=datetime.now().strftime('%X')
print(f'Received echo: {msg} at {time}')
finally:
print ('closing socket')
sock.close()

output:
$ python server.py
Got a connection from ('localhost', 10000)
$ python client.py
The time got from the server is Wed Feb 2o 19:14:15 2023

39
Program 23: Implement Connection of computers in Local Area Network.

import random
class Computer:
"""
A simulated computer in the LAN.
"""
def init (self, name):
self.name = name
self.ip_address = f"192.168.0.{random.randint(1, 254)}"

def repr (self):


return f"{self.name} ({self.ip_address})"

class Switch:
"""
A simulated switch that connects computers in the LAN.
"""
def init (self):
self.computers = []

def add_computer(self, computer):


self.computers.append(computer)

def send_message(self, source_computer, destination_computer, message):


print(f"{source_computer} sent message '{message}' to {destination_computer}")

if name == " main ":


switch = Switch()
computer1 = Computer("Computer 1")
computer2 = Computer("Computer 2")
computer3 = Computer("Computer 3")
switch.add_computer(computer1)
switch.add_computer(computer2)
switch.add_computer(computer3)
switch.send_message(computer1, computer2, "Hello, india!")

Output:
Computer 1 (192.168.1.13) sent message 'Hello, india!' to Computer 2 (192.168.1.13

40
Program 24: Implementation of Connectionless date and time.

Server.py
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
sock.bind(server_address)
while True:
print ('waiting to receive message')
data, address = sock.recvfrom(4096)
msg=data.decode()
print(msg)
if data:
sent = sock.sendto(data, address)

Client.py
import socket
from datetime import datetime
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
message = 'This is the message. It will be repeated.'
try:
sent = sock.sendto(bytes(message, 'utf-8'), server_address)
data, server = sock.recvfrom(4096)
msg=data.decode()
time=datetime.now().strftime('%X')
print(f'Received echo: {msg} at {time}')
finally:
print ('closing socket')
sock.close()

output:
$ python server.py
Got a connection from ('localhost', 10000)
$ python client.py
The time got from the server is Tue Feb29 19:14:15 2024

41
Program 25: Program for Connection-Concurrent Iterative service in which server
calculates the net salary ofan employee based on the following details sent by the client.
i) basic ii) hra iii) da iv) net- salary=basic+ hra+ da- pt- epf.

server.py
import socket

def calculate_net_salary(basic, hra, da):


# Calculate net salary based on input parameters
pt = 200 # Professional tax
epf = 0.12 * basic # Employee Provident Fund
net_salary = basic + hra + da - pt - epf
return net_salary

def handle_client_connection(client_socket):
# Receive data from client
data = client_socket.recv(1024).decode()
data = data.split(",")
basic = int(data[0])
hra = int(data[1])
da = int(data[2])

# Calculate net salary


net_salary = calculate_net_salary(basic, hra, da)

# Send net salary to client


client_socket.send(str(net_salary).encode())

# Close connection
client_socket.close()

if name == " main ":


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(5)
print("Server is listening on port 12345")

while True:
# Wait for client connection
client_socket, address = server_socket.accept()
print(f"Received connection from {address}")

# Handle client connection in a separate thread


handle_client_connection(client_socket)

Client.py
import socket
host=socket.gethostname()
port=1234
client_socket=socket.socket()

42
client_socket.connect((host,port))
message=input('Basic salary:')
client_socket.send(message.encode())
message=input('House rent allowance:')
client_socket.send(message.encode())
message=input('Transport allowance:')
client_socket.send(message.encode())
message=input('FBP allowance:')
client_socket.send(message.encode())
message=input('Statutory bonus:')
client_socket.send(message.encode())
message=input('Income tax:')
client_socket.send(message.encode())
message=input('Provident fund:')
client_socket.send(message.encode())
net_salary=int(client_socket.recv(1024).decode())
print(f'Calculated net salary: {net_salary}')
print('DISCONNECTING CLIENT')
client_socket.close()

Output:
Server is listening on port 12345
Received connection from ('
192.168.1.13,56788)
'Replied with calculation 41300
CLOSING SERVER

# Once server is started run client as follows:


$ python client.py
Basic Salary 35000
House Rent Allowance 5000
Transport Allowance 1000
Fbp Allowance 700
Statuary bonus 500
Income tax 100
Provident fund 800
Calculated net salary:41300
DISCONNECTING CLIENT

43
Program 26: Program for Connection-less Iterative service in which server calculates the
net salary of anemployee based on the following details sent by the client. i) basic ii) hra
iii) da iv) net- salary=basic+ hra+ da- pt- epf.
Server.py

import socket
host=socket.gethostname()
port=1234
server_socket=socket.socket()
server_socket.bind((host,port))
server_socket.listen()
print('SERVER STARTED')
conn, addr=server_socket.accept()
print(f'CONNECTED TO CLIENT: {str(addr)}')
basic_salary=int(conn.recv(1024).decode())
house_rent_allowance=int(conn.recv(1024).decode())
transport_allowance=int(conn.recv(1024).decode())
FBP_allowance=int(conn.recv(1024).decode())
statutory_bonus=int(conn.recv(1024).decode())
income_tax=int(conn.recv(1024).decode())
provident_fund=int(conn.recv(1024).decode())
net_salary=(basic_salary+house_rent_allowance+transport_allowance+FBP_allowance+statutory_bonus)-
(income_tax+provident_fund)
conn.send(str(net_salary).encode())
print(f'Replied with calculation{net_salary}')
print('CLOSING SERVER')
Client.py
import socket
host=socket.gethostname()
port=1234
client_socket=socket.socket()
client_socket.connect((host,port))
message=input('Basic salary:')
client_socket.send(message.encode())
message=input('House rent allowance:')
client_socket.send(message.encode())
message=input('Transport allowance:')
client_socket.send(message.encode())
message=input('FBP allowance:')
client_socket.send(message.encode())
message=input('Statutory bonus:')
client_socket.send(message.encode())
message=input('Income tax:')
client_socket.send(message.encode())
message=input('Provident fund:')
client_socket.send(message.encode())
net_salary=int(client_socket.recv(1024).decode())
print(f'Calculated net salary: {net_salary}')
print('DISCONNECTING CLIENT')
client_socket.close()

44
Output:

# Following would start a server in background.


$ python server.py
SERVER STARTED '
CONNECTED TO CLIENT: ' 192.168.1.13'
'Replied with calculation 34300
CLOSING SERVER

# Once server is started run client as follows:


$ python client.py
Basic Salary 31000
House Rent Allowance 2000
Transport Allowance 500
Fbp Allowance 500
Statuary bonus 500
Income tax 100
Provident fund 100
Calculated net salary:34300
DISCONNECTING CLIENT

45
Program 27: Write a program for error detecting code using CRC-CCITT (8-bits).

def crc_ccitt(data):
crc = 0xFFFF # Initialize CRC value to 0xFFFF
poly = 0x1021 # CRC_CCITT polynomial value
for byte in data:
crc ^= (byte << 8) # XOR the CRC value with the next byte of the data
for _ in range(8):
if crc & 0x8000: # Check if the most significant bit is 1
crc = (crc << 1) ^ poly # Shift left and XOR with the polynomial
else:
crc <<= 1 # Shift left
crc &= 0xFFFF # Mask the CRC value to 16 bits
return crc

if name == " main ":


data = b"hello world" # Data to calculate CRC_CCITT for
crc = crc_ccitt(data)
print(f"CRC_CCITT value: {hex(crc)}")

output:

CRC_CCITT value: 0xc70c

46
Program 28: Implementation of student grade server.
//Server

import socket
def calculate_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

def process_data(data):
name, score = data.split(":")
grade = calculate_grade(int(score))
return f"{name} got a {grade}"

def handle_client(conn):
data = conn.recv(1024).decode().strip()
result = process_data(data)
conn.send(result.encode())
conn.close()

if name == " main ":


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("localhost", 8000))
server_socket.listen()

print("Server started. Listening on port 8000.")

while True:
conn, addr = server_socket.accept()
print(f"New connection from {addr}")
handle_client(conn)
//client
import socket

if name == " main ":


server_address = ("localhost", 8000)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(server_address)

print("Connected to server. Enter student name and score to get grade.")

while True:
data = input("Enter name and score separated by a colon (or enter 'quit' to exit): ")
if data == "quit":
break
47
client_socket.send(data.encode())
result = client_socket.recv(1024).decode().strip()
print(f"Result: {result}")

client_socket.close()

Output:
Server started. Listening on port 8000
Connected to server. Enter student name and score to get grade.
Harry75: 85: 80
Result: B
Server: grade at server is B

48
Program 29: Write a program for distance vector algorithm to find suitable path for
transmission.

class DistanceVector:
def init (self, graph):
self.graph = graph
self.nodes = set(graph.keys())
self.distances = {node: {node: 0 if node == source else float("inf") for node in self.nodes} for source in self.nodes}
self.next_hops = {source: {destination: destination for destination in self.nodes} for source in self.nodes}
self.changed = True

def run(self):
while self.changed:
self.changed = False
for source in self.nodes:
for destination in self.nodes:
if self.distances[source][destination] != min(self.distances[source][neighbor] +
self.distances[neighbor][destination] for neighbor in self.nodes):
self.distances[source][destination] = min(self.distances[source][neighbor] +
self.distances[neighbor][destination] for neighbor in self.nodes)
self.next_hops[source][destination] = min((self.distances[source][neighbor] +
self.distances[neighbor][destination], self.next_hops[source][neighbor]) for neighbor in self.nodes)[1]
self.changed = True

def get_shortest_path(self, source, destination):


if source not in self.nodes or destination not in self.nodes:
raise ValueError("Invalid source or destination node")

return self.next_hops[source][destination]

if name == " main ":


# Define the network graph as a dictionary
graph = {
"A": {"B": 5, "D": 3},
"B": {"A": 5, "C": 2},
"C": {"B": 2, "D": 6},
"D": {"A": 3, "C": 6}
}

# Create a DistanceVector object and run the algorithm


dv = DistanceVector(graph)
dv.run()

# Print the shortest paths between nodes


print("Shortest paths:")
for source in dv.nodes:
for destination in dv.nodes:
if source != destination:
print(f"{source} -> {destination}: {dv.get_shortest_path(source, destination)}")

Output:

49
Shortest paths:
A -> B: B
A -> C: B
A -> D: D
B -> A: A
B -> C: C
B -> D: D
C -> A: B
C -> B: B
C -> D: D
D -> A: A
D -> B: B
D -> C: C

50
Program 30: Implementation of authentication server

Server.py

class AuthenticationServer:
def init (self):
self.users = {}

def add_user(self, username, password):


if username in self.users:
raise ValueError("Username already exists")
self.users[username] = password

def authenticate(self, username, password):


if username not in self.users:
return False
return self.users[username] == password

if name == " main ":


server = AuthenticationServer()

while True:
print("Enter a command:")
print(" add_user <username> <password>")
print(" authenticate <username> <password>")
print(" quit")

command = input().split()
if not command:
continue

if command[0] == "add_user":
if len(command) != 3:
print("Invalid syntax")
continue
try:
server.add_user(command[1], command[2])
print("User added successfully")
except ValueError as e:
51
print(str(e))

elif command[0] == "authenticate":


if len(command) != 3:
print("Invalid syntax")
continue
if server.authenticate(command[1], command[2]):
print("Authentication successful")
else:
print("Authentication failed")

elif command[0] == "quit":


break

else:
print("Unknown command")

Output:
Enter a command:
add_user alice password123
User added successfully
Enter a command:
authenticate alice password123
Authentication successful
Enter a command:
authenticate alice wrongpassword
Authentication failed
Enter a command:
quit

52

You might also like