network lab manual(air)

60
Computer Networks LabManual SVCE,BANGALORE-57 Department Of Computer Science and Engineering Page 1 NETWORKS LABORATORY MANUAL For VII SEMESTER DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING SRI VENKATESHWARA COLLEGE OF ENGINEERING VIDYANAGAR BANGALORE-562157

Upload: raju7433

Post on 18-Apr-2015

99 views

Category:

Documents


3 download

TRANSCRIPT

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 1

NETWORKS LABORATORY MANUAL

For

VII SEMESTER

DEPARTMENT OF COMPUTER SCIENCE&

ENGINEERINGSRI VENKATESHWARA COLLEGE OF ENGINEERING

VIDYANAGARBANGALORE-562157

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 2

NETWORKS LABORATORY(COMMON TO CSE & ISE)

Subject Code :06CSL77 IA Marks :25No.Of Practical Hours/Week :03 Exam Hours :03Total No. Of Practical Hours :42 Exam Marks :05

Note : Student is required to solve one problem from PART-A and one problemfrom PART-B. Both the parts have equal weightage.

PART A – SIMULATION EXERCISES

The following experiments shall be conducted using either NS228/OPNET or anyother simulators.

1. Simulate a three nodes point-to-point network with duplex links between them. Setthe queue size vary the bandwidth and find the number of packets dropped.

2. Simulate a four node point-to-point network, and connect the links as follows: n0-n2,n1-n2 and n2-n3. Apply TCP agent between n0-n3 and UDP n1-n3. Apply relevantapplications over TCP and UDP agents changing the parameter and determine thenumber of packets by TCP/UDP.

3. Simulate the different types of Internet traffic such as FTP a TELNET over a networkand analyze the throughput.

4. Simulate the transmission of ping messaged over a network topology consisting of 6nodes and find the number of packets dropped due to congestion.

5. Simulate an Ethernet LAN using N-nodes(6-10), change error rate and data rate andcompare the throughput.

6. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes anddetermine collision across different nodes.

7. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and plotcongestion window for different source/destination.

8. Simulate simple ESS and with transmitting nodes in wire-less LAN by simulation anddetermine the performance with respect to transmission of packets.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 3

PART B

The following experiments shall be conducted using C/C++.

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

2. Write a program for frame sorting technique used in buffers.

3. Write a program for distance vector algorithm to find suitable path for transmission.

4. Using TCP/IP sockets, write a client-server program to make client sending the file

name and the server to send back the contents of the requested file if present.

5. Implement the above program using as message queues or FIFOs as IPC channels.

6. Write a program for simple RSA algorithm to encrypt and decrypt the data.

7. Write a program for Hamming Code generation for error detection and correction.

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

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 4

PART A Programs

Start up

1. Open three terminalsa) in terminal 1 at command prompt run dispatcher( root@localhost#

dispatcher)b) in terminal 2 at command prompt run coordinator( root@localhost#

coordinator)c) in terminal 3 at command prompt run nctunsclient( root@localhost#

nctunsclient)

2. After the above steps NCTUns starting screen will appear.

3. To draw the network topology perform the following stepsChoose Menu-> File-> Operating Mode-> D(draw mode), draw the requiredtopology or change the existing simulation topology.(drag and drop)

4 Once topology is drawn , set the node property by switching to “Edit property”mode E

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 5

5 Configure the node with appropriate commands at source and destination6 Run the Simulation menu simulation run7 Play back the simulation.

Program No 1

1. Simulate a three-node point-to-point network with a duplex link between them. Setthe queue size and vary the bandwidth and find the number of packets dropped.

Topology:-

STEPS:

To draw a network topology, do the following steps:

1. Select the host icon on the toolbar and drag it onto the working window.

Repeat this for another host icon. Select the link icon on the toolbar and

drag it on the screen from host [node 1] to the hub and again from host

[node2] to the hub. Here the hub acts as node 3 in the point-to-point

network. This leads to the creation of the 3-node point-to-point network

topology.

[We can see the ip address of the host by moving the mouse

pointer on host ]

2. Save this topology as a filename.tpl

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 6

To configure the network devices, do the following steps:

At Sender

1. Double click on host [node-1], a host dialog box will open up

2. Click on the Add button and enter the command (at the sender)

stg [-u udp][-t duration (sec)] [-p port number]HostIPaddr and set the simulation

time 0 to 40 sec then click ok

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 7

3. Click on the node editor and you can see the different layers-interface,

ARP, FIFO, MAC, TCPDUMP, Physical layers.

4. Select MAC and then select full-duplex for switches and routers and half- duplex for

hubs, and check the log packet statistics check box ,

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 8

5.Select output throughput log file etc (at sender), select the number of drop packets,number of collisions.

Click the OK button.At Receiver: Steps

1. Click on the Add button and enter the command (at the receiver)

rtg [-t] [-w log] [-p port number] and click OK

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 9

2. Click on the node editor and you can see the different layers-interface, ARP,FIFO, MAC, TCPDUMP, Physical layers.

3. Select input throughput log file etc (at receiver), select the number of drop

packets, number of collisions.

Click ok.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 10

To RUN the Simulation

1. Now click on the R button (Run simulation). By doing so a user can

run/pause/continue/stop/abort/disconnect/reconnect/submit a simulation. No

simulation settings can be changed in this mode.

2. Now go to the Menu->Simulation->Run. Executing this command will submit the

current simulation job to one available simulation server managed by the

dispatcher. When the simulation server is executing, the user will see the time

knot at the bottom of the screen move. The time knot reflects the current virtual

time (progress) of the simulation case.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 11

To playback the simulation

To start the playback, the user can left-click the start icon ( |>) of the time bar located

at the bottom. The animation player will then start playing the recorded packet

animation.

.

The results are stored in file.results folder(“file” is the same name given by the

user to the simulation file).

You will see the following log files in the folder: file.results

Filename.8023_N2_P1_OutThrput.log

Filename.8023_N3_P1_InThrput.log

Filename..8023_n2_p1_coll.log

Filename.8023_N2_P1_Drop.log

Here the drop and collision files do not have data, because of point to point connection

no drop, no collision

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 12

Graph can be plotted during the play mode:

To plot the graph on menu Tools plot graph open file name

Graph for 10 mbps bandwidth

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 13

Change the bandwidth say, 9 Mbps or less , and run the simulation and compare

the two results. To view the results go to the filename. results folder.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 14

To change the setting of the graph and X-values and Y-values ,go to options generalsetting

Inference: Since it is a point to point connection and no of nodes are only 2 ,so there isno chance of drop and collision , what ever the data sent from source is received by thereceiver.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 15

Program No 2

2. Simulate a four-node point-to-point network and connect the link as follows:Apply a TCP agent between n0 to n3 and apply a UDP agent between n1 andn3. Apply relevant applications over TCP and UDP agents changing theparameters and determine the number of packets sent by two agents.

Topology:-

Sender:-stcp –p 3000 –l 1024 1.0.1.3stg –u 1024 1.0.1.3

Receiver:-rtcp –p 3000 –l 1024rtg –u 3000

Parameters:-Throughput of incoming and outgoing Packets

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 16

Program No 3

3. Simulate the different types of Internet traffic such as FTP, TELNET over anetwork and analyze the throughput.

To draw a network topology, do the following steps:

Step 1: Select the host icon on the toolbar and drag it onto the working window.

Repeat this for another host icon. Select the link icon on the toolbar and

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 17

Draw the topology as shown above.

[We can see the ip address of the host by moving the mouse

pointer on host ]

Step 2: Save this topology as a filename.tpl

To configure the network devices, do the following steps:

Step 1: click on host , a host dialog box will open up

Step 2: Click on the Add button and enter the command (at the sender)

node 1: For FTP stcp –p 21 –l 1024 1.0.1.4

node 2: For Telnet stcp –p 23 –l1024 1.0.1.4and set the simulation time 0 to 40 sec then click ok

Step 3: Click on the node editor and you can see the different layers-interface,

ARP, FIFO, MAC, TCPDUMP, Physical layers.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 18

Step 4: Select MAC and then select full-duplex for switches and routers and

half-duplex for hubs, and check the log packet statistics check

box ,

Step5: Select output throughput log file etc (at sender), select the number of drop

Packets, Output ThroughPut.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 19

Click the OK button.

Step 6: At Receiver:

Click on the Add button and enter the command (at the receiver) node 4

For FTP rtcp -p 21 –l 1024

For TELNET rtcp -p 23 –l 1024 and click OK

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 20

Step 7: Click on the node editor and you can see the different layers-interface, ARP,

FIFO, MAC, TCPDUMP, Physical layers.

Step 8: Select input throughput log file etc (at receiver), select the number of drop

packets, number of collisions.

Click ok.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 21

To RUN the Simulation

Step 1: Now click on the R button (Run simulation). By doing so a user can

run/pause/continue/stop/abort/disconnect/reconnect/submit a simulation. No

simulation settings can be changed in this mode.

Step 2: Now go to the Menu->Simulation->Run. Executing this command will submit the

current simulation job to one available simulation server managed by the

dispatcher. When the simulation server is executing, the user will see the time

knot at the bottom of the screen move. The time knot reflects the current virtual

time (progress) of the simulation case.

To playback the simulation

To start the playback, the user can left-click the start icon ( |>) of the time bar located

at the bottom. The animation player will then start playing the recorded packet

animation.

The results are stored in file.results folder(“file” is the same name given by the user

to the simulation file).You will see the following log files in the folder: file.results

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 22

Filename.8023_N1_P1_OutThrput.logFilename.8023_N4_P1_InThrput.log

Filename..8023_n4_p1_coll.log

Filename.8023_N4_P1_Drop.log

Here the drop and collision files do not have data, because of in point to point connection

no drop, no collision

Graph can be plotted during the play mode

To plot the graph on menu Tools plot graph open file name

Graph for out put Thruput FTP Traffic

Graph for Input Thruput , FTP Traffic

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 23

Graph For output Thrput, TELNET Traffic

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 24

Graph for input Thrput (Telnet Traffic)

To change the setting of the graph and X-values and Y-values ,go to options generalsetting

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 25

Program No 4

4. Simulate the transmission of ping messages over a network topology consisting of6 nodes and find the number of packets dropped due to congestion.

Topology:-

Sender:-stcp –p 2000 –l 1024 1.0.1.4

Receiver:-rtcp –p 2000 –l 1024

Command Console:-Goto tools-> simulation time and change Simulation time to 100. During runmode, double click host 2 and then click command console. And execute thefollowing command.

ping 1.0.1.4

Parameters:-Drop Packets and Collision Packets.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 26

Program No 5

5. Simulate an Ethernet LAN using N nodes (6-10), change error rate and data rateand compare throughput.

Topology:-

Sender:-stcp –p 2000 –l 1024 1.0.1.4

Receiver:-rtcp –p 2000 –l 1024

Double click on receiver link and change BER to 0.000001, Run

Again. Parameters:-Throughput of outgoing Packets

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 27

Program No 6

6. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes anddetermine collisions across different nodes.

Topology:-

Sender:-stcp –p 2000 –l 1024 1.0.1.4

Receiver:-rtcp –p 2000 –l 1024

Parameters:-Collision Packets and Drop Packets (Optional)

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 28

Program No 7

7. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and plotcongestion window for different source/destination.

Topology:-

Sender:-stcp –p 2000 –l 1024 1.0.1.4

Receiver:-rtcp –p 2000 –l 1024

Parameters:-Receiver side Collision Packets and Drop Packets

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 29

Program No 8

8. Simulate simple BSS and with transmitting nodes in wireless LAN by simulation anddetermine the performance with respect to transmission of packets.

Topology:-

Click on “access point”. Goto wireless interface and tick on “show transmission rangeand then click OK.

Double click on Router -> Node Editor and thenLeft stack -> throughput of Incoming packetsRight stack -> throughput of Outgoing packets

Select mobile hosts and access points then click on.Tools -> WLAN mobile nodes-> WLAN Generate infrastructure.

Subnet ID: Port number of router (2)Gateway ID: IP address of router

Mobile Host 1ttcp –t –u –s –p 3000 1.0.1.1

Mobile Host 1ttcp –t –u –s –p 3001 1.0.1.1

Host(Receiver)ttcp –r –u –s –p 3000ttcp –r –u –s –p 3001

Run and then play to plot the graph.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 30

PART B Programs

Experiment No 1CRC

Problem StatementWrite a program for error detecting code using CRC-CCITT (16-bits).

TheoryIt does error checking via polynomial division. In general, a bit string

bn-1bn-2bn-3…b2b1b0

As

bn-1Xn-1+ bn-2 Xn-2

+ bn-3 Xn-3+ …b2 X2

+ b1 X1+

b0Ex: -

10010101110

As

X10 + X7 + X5 + X3 + X2 + X1

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 31

All computations are done in modulo 2

Algorithm:-1. Given a bit string, append 0S to the end of it (the number of 0s is the same as the degree of

the generator polynomial) let B(x) be the polynomial corresponding to B.2. Divide B(x) by some agreed on polynomial G(x) (generator polynomial) and determine

the remainder R(x). This division is to be done using Modulo 2 Division.3. Define T(x) = B(x) –R(x)

(T(x)/G(x) => remainder 0)

4. Transmit T, the bit string corresponding to T(x).5. Let T’ represent the bit stream the receiver gets and T’(x) the associated polynomial. The

receiver divides T1(x) by G(x). If there is a 0 remainder, the receiver concludes T = T’and no error occurred otherwise, the receiver concludes an error occurred and requires aretransmission.

Program-Name : crc.c#include<stdio.h>#include<unistd.h>#include<string.h>int crc(char *input,char *output,char *gp,int mode){int j,k;strcpy(output,input);if(mode){for(j=1; j<strlen(gp); j++)strcat(output,"0");}for(j=0; j<strlen(input); j++)if(*(output+j) == '1')for(k=0; k<strlen(gp); k++){if (((*(output+j+k) =='0') && (gp[k] == '0') || (*(output+j+k) == '1') && (gp[k] == '1')))*(output+j+k)='0';else*(output+j+k)='1';}for(j=0; j<strlen(output); j++)if(output[j] == '1')return 1;return 0;}

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 32

int main(){char input[50],output[50];char recv[50], gp[50];system("clear");printf("\n Enter the input message in binary\n");scanf("%s",input);printf("\n Enter the generetor polynomial\n");scanf("%s",gp);crc(input,output,gp,1);printf("\n The transmitted message is %s%s\n",input,output+strlen (input));printf("\n\n Enter the recevied message in binary \n");scanf("%s",recv);if(!crc(recv,output,gp,0))printf("\n No error in data\n");elseprintf("\n Error in data transmission has occurred\n");}COMPILE AND RUN:-OUTPUT$ cc –o crc crc.c$ ./crc

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 33

Experiment No 2Frame Sorting

Problem StatementWrite a program for frame sorting technique used in buffers.

TheoryThe data link layer divides the stream of bits received from the network layer into manageable

data units called frames.If frames are to be distributed to different systems on the network, the Data link layer adds a

header to the frame to define the sender and/or receiver of the frame.Each Data link layer has its own frame format. One of the fields defined in the format is the

maximum size of the data field. In other words, when datagram is encapsulated in a frame, thetotal size of the datagram must be less than this maximum size, which is defined by restrictionimposed by the hardware and software used in the network.

IP Datagram

Header MTU Trailer

The value of MTU differs from one physical network to anotherIn order to make IP protocol portable/independent of the physical network, the packagers

decided to make the maximum length of the IP datagram equal to the largest Maximum TransferUnit (MTU) defined so far. However for other physical networks we must divide the datagrams tomake it possible to pass through these networks. This is called fragmentation.

When a datagram is fragmented, each fragmented has its own header. A fragmented datagrammay itself be fragmented if it encounters a network with an even smaller MTU. In another words,a datagram may be fragmented several times before it reached the final destination and also, thedatagrams referred to as (frames in Data link layer) may arrives out of order at destination. Hencesorting of frames need to be done at the destination to recover the original data.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 34

Program-Name : frame.c#include<stdio.h>struct frame{int fno;char fdata[25];};struct frame arr[20];int n;void sort(){int i,j;struct frame temp;for(i=0;i<=n-1;i++){for(j=0;j<n-i-1;j++)if(arr[j].fno > arr[j+1].fno){temp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}int main(){int i;system("clear");printf("\n Enter the number of frames :");scanf("%d",&n);printf("\n enter the rrame sequence number and frame content\n");for(i=0;i<n;i++)scanf("%d%s",&arr[i].fno,arr[i].fdata);sort();printf("\n the frames in sequence are\n");for(i=0;i<n;i++){printf("01111110 %d\t%s 01111110\n",arr[i].fno,arr[i].fdata);}}COMPILE AND RUN:-OUTPUT$ cc –o frame frame.c$ ./frame

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 35

Experiment No 3Distance Vector Routing

Problem StatementWrite a program for distance vector algorithm to find suitable path for transmission.

TheoryRouting algorithm is a part of network layer software which is responsible for deciding which

output line an incoming packet should be transmitted on. If the subnet uses datagram internally,this decision must be made anew for every arriving data packet since the best route may havechanged since last time. If the subnet uses virtual circuits internally, routing decisions are madeonly when a new established route is being set up. The latter case is sometimes called sessionrouting, because a rout remains in force for an entire user session (e.g., login session at a terminalor a file).

Routing algorithms can be grouped into two major classes: adaptive and nonadaptive.Nonadaptive algorithms do not base their routing decisions on measurement or estimates ofcurrent traffic and topology. Instead, the choice of route to use to get from I to J (for all I and J) iscompute in advance, offline, and downloaded to the routers when the network ids booted. Thisprocedure is sometime called static routing.

Adaptive algorithms, in contrast, change their routing decisions to reflect changes in thetopology, and usually the traffic as well. Adaptive algorithms differ in where they get information(e.g., locally, from adjacent routers, or from all routers), when they change the routes (e.g., every

T sec, when the load changes, or when the topology changes), and what metric is used foroptimization (e.g., distance, number of hops, or estimated transit time).

Two algorithms in particular, distance vector routing and link state routing are the mostpopular. Distance vector routing algorithms operate by having each router maintain a table (i.e.,vector) giving the best known distance to each destination and which line to get there. Thesetables are updated by exchanging information with the neighbors.

The distance vector routing algorithm is sometimes called by other names, including thedistributed Bellman-Ford routing algorithm and the Ford-Fulkerson algorithm, after theresearchers who developed it (Bellman, 1957; and Ford and Fulkerson, 1962). It was the originalARPANET routing algorithm and was also used in the Internet under the RIP and in earlyversions of DECnet and Novell’s IPX. AppleTalk and Cisco routers use improved distance vectorprotocols.

In distance vector routing, each router maintains a routing table indexed by, and containingone entry for, each router in subnet. This entry contains two parts: the preferred out going line touse for that destination, and an estimate of the time or distance to that destination. The metricused might be number of hops, time delay in milliseconds, total number of packets queued alongthe path, or something similar.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 36

The router is assumed to know the “distance” to each of its neighbor. If the metric is hops, thedistance is just one hop. If the metric is queue length, the router simply examines each queue. Ifthe metric is delay, the router can measure it directly with special ECHO packets hat the receiverjust time stamps and sends back as fast as possible.

The Count to Infinity Problem.Distance vector routing algorithm reacts rapidly to good news, but leisurely to bad

news. Consider a router whose best route to destination X is large. If on the next exchangeneighbor A suddenly reports a short delay to X, the router just switches over to using the lineto A to send traffic to X. In one vector exchange, the good news is processed.

To see how fast good news propagates, consider the five node (linear) subnet offollowing figure, where the delay metric is the number of hops. Suppose A is down initially andall the other routers know this. In other words, they have all recorded the delay to A as infinity.

A B C D E A B C D E

Initially 1 2 3 4 Initially1 After 1 exchange 3 2 3 4 After 1 exchange1 2 After 2 exchange 3 3 3 4 After 2 exchange1 2 3 After 3 exchange 5 3 5 4 After 3 exchange1 2 3 4 After 4 exchange 5 6 5 6 After 4 exchange

7 6 7 6 After 5 exchange7 8 7 8 After 6 exchange

:

Many ad hoc solutions to the count to infinity problem have been proposed in theliterature, each one more complicated and less useful than the one before it. The splithorizon algorithm works the same way as distance vector routing, except that the distance toX is not reported on line that packets for X are sent on (actually, it is reported as infinity). Inthe initial state of right figure, for example, C tells D the truth about distance to A but C tellsB that its distance to A is infinite. Similarly, D tells the truth to E but lies to C.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 37

Program-Name :dv.c

#include<stdio.h>struct node{unsigned dist[20];unsigned from[20];}rt[10];int main(){int dmat[20][20];int n=i=j=k=0,count=0;system("clear");printf("Enter The Number Of Nodes\n");scanf("%d",&n);printf("Enter The Cost Matrix\n");for(i=0;i<n;i++)for(j=0;j<n;j++){scanf("%d",&dmat[i][j]);dmat[i][i]=0;rt[i].dist[j]=dmat[i][j];rt[i].from[j]=j;}do{count=0;for(i=0;i<n;i++)for(j=0;j<n;j++)for(k=0;k<n;k++)if(rt[i].dist[j]>dmat[i][k]+rt[k].dist[j]){rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];rt[i].from[j]=k;count++;}}

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 38

while (count!=0);for(i=0;i<n;i++){printf("State Value For Router %d Is\n",i);for(j=0;j<n;j++){printf("\t\tVia %d Distance %d",rt[i].from[j],rt[i].dist[j]);}}}COMPILE AND RUN:-OUTPUT$ cc –o dv dv.c$ ./dvEnter The Number Of Nodes3Enter The Cost Matrix0 3 67 0 95 7 0State Value For Router 0 Is

Via 0 Distance 0

Via 1 Distance 3

Via 2 Distance 6

State Value For Router 1 Is

Via 0 Distance 7

Via 1 Distance 0

Via 2 Distance 9

State Value For Router 2 Is

Via 0 Distance 5

Via 1 Distance 7

Via 2 Distance 0

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 39

Experiment No 4TCP Socket

Problem StatementUsing TCP/IP sockets, write a client-server program to make client sending the file name and theserver to send back the contents of the requested file if present.

Algorithm (Client Side)1. Start.2. Create a socket using socket() system call.3. Connect the socket to the address of the server using connect() system call.4. Send the filename of required file using send() system call.5. Read the contents of the file sent by server by recv() system call.6. Stop.

Algorithm (Server Side)1. Start.2. Create a socket using socket() system call.3. Bind the socket to an address using bind() system call.4. Listen to the connection using listen() system call.5. accept connection using accept()6. Receive filename and transfer contents of file with client.7. Stop.

Header Filename: inet.h#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<arpa/inet.h>#include<fcntl.h>#include<string.h>#define SERV_TCP_PORT 6880#define SERV_HOST_ADDR "127.0.0.1"

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 40

Program-Name: Client.c

#include"inet.h"int main(){int sockfd;struct sockaddr_in serv_addr,cli_addr;char filename[100],buf[1000];int n;serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR);serv_addr.sin_port=htons(SERV_TCP_PORT);if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)printf("Client:cant open stream socket\n");elseprintf("Client:stream socket opened successfully\n");if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)printf("Client:cant connect to server\n");elseprintf("Client:connected to server successfully\n");printf("\n Enter the file name to be displayed :");scanf("%s",filename);write(sockfd,filename,strlen(filename));printf("\n filename transfered to server\n");n=read(sockfd,buf,1000);if(n < 0)printf("\n error reading from socket");printf("\n Client : Displaying file content of %s\n",filename);fputs(buf,stdout);close(sockfd);exit(0);}

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 41

Program-Name: Server.c#include"inet.h"int main(){int sockfd,newsockfd,clilen;struct sockaddr_in cli_addr,serv_addr;char filename[25],buf[1000];int n,m=0;int fd;if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)printf("server:cant open stream socket\n");elseprintf("server:stream socket opened successfully\n");serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);serv_addr.sin_port=htons(SERV_TCP_PORT);if((bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)))<0)printf("server:cant bind local address\n");elseprintf("server:bound to local address\n");listen(sockfd,5);printf("\n SERVER : Waiting for client...\n");for(;;){clilen=sizeof(cli_addr);newsockfd=accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);if(newsockfd<0)printf("server:accept error\n");elseprintf("server:accepted\n");n=read(newsockfd,filename,25);filename[n]='\0';printf("\n SERVER : %s is found and ready to transfer\n",filename);fd=open(filename,O_RDONLY);n=read(fd,buf,1000);buf[n]='\0';write(newsockfd,buf,n);printf("\n transfer success\n");close(newsockfd);exit(0);}}

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 42

COMPILE AND RUN:-OUTPUT- open first terminal, compile and run server there$ cc –o ser Server.c$ ./ser- open second terminal, compile and run client there$ cc –o cli Client.c$ ./cli

Experiment No 5FIFO IPC

Problem StatementImplement the above program using as message queues or FIFO as IPC channels.

Algorithm (Client Side)1. Start.2. Open well known server FIFO in write mode.3. Write the pathname of the file in this FIFO and send the request.4. Open the client specified FIFO in read mode and wait for reply.5. When the contents of the file are available in FIFO, display it on the terminal6. Stop.

Algorithm (Server Side)1. Start.2. Create a well known FIFO using mkfifo()3. Open FIFO in read only mode to accept request from clients.4. When client opens the other end of FIFO in write only mode, then read the contents and

store it in buffer.5. Create another FIFO in write mode to send replies.6. Open the requested file by the client and write the contents into the client specified FIFO

and terminate the connection.7. Stop.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 43

Program-Name: fclient.c#include<stdio.h>#include<fcntl.h>#include<string.h>#include<stdlib.h>#include<sys/types.h>#include<sys/stat.h>#include<unistd.h>int main(){char filename[100],buf[300];int num,num2,fl,fd,fd2;mknod("fifo1",S_IFIFO | 0666,0);mknod("fifo2",S_IFIFO | 0666,0);fd=open("fifo1",O_WRONLY);printf("CLient Online! \n CLIENT enter the path...\n\n");scanf("%s",filename);write(fd,filename,strlen(filename));printf("\n waiting for reply...\n");fd2=open("fifo2",O_RDONLY);num2=read(fd2,buf,300);buf[num2]='\0';printf("\n File received ..the contents are...\n");fputs(buf,stdout);unlink("fifo1");unlink("fifo2");exit(1);}

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 44

Program-Name: fserver.c#include<stdio.h>#include<fcntl.h>#include<stdlib.h>#include<string.h>#include<sys/types.h>#include<sys/stat.h>#include<unistd.h>int main(){char filename[100],buf[300],buf1[300];int num,num2,n,filesize,fl,fd,fd2;mknod("fifo1",S_IFIFO | 0666,0);mknod("fifo2",S_IFIFO | 0666,0);printf("\n Server Online\n");fd=open("fifo1",O_RDONLY);printf("Client Online! Waiting for request...\n\n");while(1){num = read(fd,filename,100);filename[num]='\0';fl=open(filename,O_RDONLY);printf("\n Sever: %s is found!\n transferring the contents\n",filename);filesize=lseek(fl,0,2);printf("\n File size is %d\n",filesize);lseek(fl,0,0);n=read(fl,buf1,filesize);buf1[n]='\0';fd2=open("fifo2",O_WRONLY);write(fd2,buf1,strlen(buf1));printf("\n SERVER :Transfer completed\n");exit(1);}unlink("fifo1");unlink("fifo2");}

COMPILE AND RUN:-OUTPUT- open first terminal, compile and run server there$ cc –o ser fserver.c$ ./ser

- open second terminal, compile and run client there$ cc –o cli fclient.c$ ./cli

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 45

Experiment No 6RSA Algorithm

Problem StatementWrite a program for simple RSA algorithm to encrypt and decrypt the data.

TheoryCryptography has a long and colorful history. The message to be encrypted, known as the

plaintext, are transformed by a function that is parameterized by a key. The output of theencryption process, known as the ciphertext, is then transmitted, often by messenger or radio. Theenemy, or intruder, hears and accurately copies down the complete ciphertext. However, unlikethe intended recipient, he does not know the decryption key and so cannot decrypt the ciphertexteasily. The art of breaking ciphers is called cryptanalysis the art of devising ciphers(cryptography) and breaking them (cryptanalysis) is collectively known as cryptology.

There are several ways of classifying cryptographic algorithms. They are generallycategorized based on the number of keys that are employed for encryption and decryption, andfurther defined by their application and use. The three types of algorithms are as follows:1. Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption. It is

also known as symmetric cryptography.2. Public Key Cryptography (PKC): Uses one key for encryption and another for decryption. It

is also known as asymmetric cryptography.3. Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information

Public-key cryptography has been said to be the most significant new development incryptography. Modern PKC was first described publicly by Stanford University professor MartinHellman and graduate student Whitfield Diffie in 1976. Their paper described a two-key cryptosystem in which two parties could engage in a secure communication over a non-securecommunications channel without having to share a secret key.

Generic PKC employs two keys that are mathematically related although knowledge of onekey does not allow someone to easily determine the other key. One key is used to encrypt theplaintext and the other key is used to decrypt the ciphertext. The important point here is that itdoes not matter which key is applied first, but that both keys are required for the process to work.Because pair of keys is required, this approach is also called asymmetric cryptography.

In PKC, one of the keys is designated the public key and may be advertised as widely as theowner wants. The other key is designated the private key and is never revealed to another party. Itis straight forward to send messages under this scheme.

The RSA algorithm is named after Ron Rivest, Adi Shamir and Len Adleman, who invented itin 1977. The RSA algorithm can be used for both public key encryption and digital signatures. Itssecurity is based on the difficulty of factoring large integers.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 46

Algorithm1. Generate two large random primes, P and Q, of approximately equal size.2. Compute N = P x Q3. Compute Z = (P-1) x (Q-1).4. Choose an integer E, 1 < E < Z, such that GCD (E, Z) = 1

5. Compute the secret exponent D, 1 < D < Z, such that E x D 1 (mod Z)6. The public key is (N, E) and the private key is (N, D).

Note: The values of P, Q, and Z should also be kept secret.The message is encrypted using public key and decrypted using private key.

An example of RSA encryption1. Select primes P=11, Q=3.2. N = P x Q = 11 x 3 = 33

Z = (P-1) x (Q-1) = 10 x 2 = 203. Lets choose E=3

Check GCD(E, P-1) = GCD(3, 10) = 1 (i.e. 3 and 10 have no common factors except 1),and check GCD(E, Q-1) = GCD(3, 2) = 1therefore GCD(E, Z) = GCD(3, 20) = 1

4. Compute D such that E x D 1 (mod Z)compute D = E^-1 mod Z = 3^-1 mod 20find a value for D such that Z divides ((E x D)-1)find D such that 20 divides 3D-1.Simple testing (D = 1, 2, ...) gives D = 7Check: (E x D)-1 = 3.7 - 1 = 20, which is divisible by Z.

5. Public key = (N, E) = (33, 3)Private key = (N, D) = (33, 7).

Now say we want to encrypt the message m = 7,Cipher code = M^E mod N

= 7^3 mod 33= 343 mod 33= 13.

Hence the ciphertext c = 13.

To check decryption we compute Message’ = C^D mod N= 13^7 mod 33= 7.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 47

Note that we don't have to calculate the full value of 13 to the power 7 here. We can make useof the fact that a = bc mod n = (b mod n).(c mod n) mod n so we can break down a potentiallylarge number into its components and combine the results of easier, smaller calculations tocalculate the final value.

Program-Name : rsa.c#include<math.h>#include<stdlib.h>#include<stdio.h>//Function To Compute gcd Of Two Numbers.int gcd(long m,long n){while(n!=0){long r=m%n;m=n;n=r;}return m;}//Function To Perform RSAint rsa(char *message){long p=0,q=0,n=0,e=0,d=0,phi=0;long nummes[100]={0};long encrypted[100]={0},decrypted[100]={0};long i=0,j=0,nofelem=0;/*Step 1*/printf("\nenter value of p and q\n");scanf("%d%d",&p,&q);/*Step 2*/n=p*q;/*Step 3*/phi=(p-1)*(q-1);/*Step 4*/for(i=2;i<phi;i++)if(gcd(i,phi)==1) break;e=i;

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 48

/*Step 5*/for(i=2;i<phi;i++)if((e*i-1)%phi==0)break;d=i;/*Step 6*/for(i=0;i<strlen(message);i++)nummes[i]=message[i]-96;nofelem=strlen(message);/*Step 7*/for(i=0;i<nofelem;i++){encrypted[i]=1;for(j=0;j<e;j++)encrypted[i] =(encrypted[i]*nummes[i])%n;}printf("\n Encrypted message\n");for(i=0;i<nofelem;i++) printf(" %ld ",encrypted[i]);/*Step 8*/for(i=0;i<nofelem;i++){decrypted[i]=1;for(j=0;j<d;j++)decrypted[i]=(decrypted[i]*encrypted[i])%n;}printf("\n Decrypted message\n ");for(i=0;i<nofelem;i++) printf("%c",(char)(decrypted[i]+96));return 0;}int main(){char *msg;printf("Enter The Message To Be Encrypted\n");scanf("%s",msg);rsa(msg);}COMPILE AND RUN:-OUTPUT$ cc –o rsa rsa.c$ ./rsa

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 49

Experiment No 7Hamming Codes

Problem StatementWrite a program for Hamming Code generation for error detection and correction

TheoryHamming codes are used for detecting and correcting single bit errors in transmitted data. This

requires that 3 parity bits (check bits) be transmitted with every 4 data bits. The algorithm iscalled A(7, 4) code, because it requires seven bits to encode 4 bits of data.

Eg:Bit String

000Parity Bit

0Verification

0 + 0 + 0 + 0 = 0001 1 0 + 0 + 1 + 1 = 0010 1 0 + 1 + 0 + 1 = 0011 0 0 + 1 + 1 + 0 = 0100 1 1 + 0 + 0 + 1 = 0101 0 1 + 0 + 1 + 0 = 0110 0 1 + 0 + 1 + 0 = 0111 1 1 + 1 + 1 + 1 = 0

Parity types:Even: - Even number of 1’s is present, i.e. the modulo 2 sum of the bits is 0.Odd: - Odd number of 1’s is present, i.e. the modulo 2 sum of the bits is 1.

Given data bits D1, D2, D3 and D4, A (7, 4) Hamming code may define parity bits P1, P2 andP3 as,

P1=D2+D3+D4P2=D1+D3+D4P3=D1+D2+D4

There are 4 equations for a parity bit that may be used in Hamming codes,

P4=D1+D2+D3

Valid Hamming codes may use any 3 of the above 4 parity bit definitions. Valid Hammingcodes may also place the parity bits in any location within the block of 7 data and parity bits.

One method for transferring 4 bits of data into a 7 bit Hamming code word is to use a 4x7generate matrix [G] defined to be the 1x4 vector [D1 D2 D3 D4].

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 50

Its possible to create a 4x7 generator matrix [G] such that the product modulo 2 of d and [G](D[G]) is the desired 1x7 Hamming code word.For example each data bits can be represented with in a column vector as follows.

1 0 0 0

0 1 0 0

0 0 1 0

0 0 0 1

D1=D2=D3=D4

And represent each parity bit with a column vector continuing a 1 in the row corresponding toeach data bit included in the computation and a zero in all other rows.

0 1 1

1 0 1P1= P2= P3=

1 1 01 1 1

And

0 1 1 1 0 0 01 0 1 0 1 0 0

G=1 1 0 0 0 1 01 1 1 0 0 0 1

P1 P2 P3 D1 D2 D3 D4

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 51

0 1 1 1 0 0 0

1 0 1 0 1 0 0

1 1 0 0 0 1 0

1 1 1 0 0 0 1

EncodingThe process to encode the data value 1010 using the Hamming code defined by the G matrix is

as follows: -

[1010]

(1*0)+ (0*1)+ (1*1)+ (0*1) 0+0+1+0 1(1*1)+ (0*0)+ (1*1)+ (0*1) 1+0+1+0 0

(1*1)+ (0*1)+ (1*0)+ (0*1) 1+0+0+0 1= (1*1)+ (0*0)+ (1*0)+ (0*0) = 1+0+0+0 = 1

(1*0)+ (0*1)+ (1*0)+ (0*0) 0+0+0+0 0(1*0)+ (0*0)+ (1*1)+ (0*0) 0+0+1+0 1(1*0)+ (0*0)+ (1*0)+ (0*1) 0+0+0+0 0

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 52

DecodingThe first step is to check the parity bits to determine if there is an error. Arithmetically, parity

may be checked as follows: -P1 = D2+D3+D4 = 0+1+1 = 0P2 = D1+D3+D4 = 1+1+1 = 1P3 = D1+D2+D4 = 1+0+1 = 0

Parity may also be validated by using matrix operation. A 3x7 parity check matrix [H] may beconstructed such that row 1 contains 1s in the position of the first parity bits and all the data bitsthat are included in its parity calculation. Using this, matrix [H] may be defined as follows: -

1 0 0 0 1 1 1H= 0 1 0 1 0 1 1

0 0 1 1 1 0 13rd Bit Parity

2nd Bit Parity

1st Bit Parity

Multiplying the 3x7 matrix [H] by a 7x1 matrix representing the encoded data produces a 3x1matrix called the Syndrome.

If the syndrome is all 0’s the encoded data is error free. If the syndrome has a non-zero value,flipping the encoded bit that is in the position of the column matching the syndrome will result ina valid code word.Ex: -Suppose the data received is 1011011, Then

10

1 0 0 0 1 1 1 1 (1*1)+(0*0)+(0*1)+(0*1)+(1*0)+(1*1)+(1*1) 1

0 1 0 1 0 1 1 1 = (0*1)+(1*0)+(0*1)+(1*1)+(0*0)+(1*1)+(1*1) = 1

0 0 1 1 1 0 1 0 (0*1)+(0*0)+(1*1)+(1*1)+(1*0)+(0*1)+(1*1) 11

1

Looking back at the matrix [H] the 7th column is all 1s so the 7th bit is the bit that has anerror.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 53

Program-Name: ham.c#include<stdio.h>#include<unistd.h>#include<math.h>int main(){int i,j;char data[4];int d1[5],d2[5],d3[5],d4[5];int p1[5],p2[5],p3[5];int gmatrix[4][8];int encode[7]={0,0,0,0,0,0,0};int edata[7]={0,0,0,0,0,0,0};int errdig;int syn[3]= {0,0,0};int hmatrix[3][7] = { 1,0,0,0,1,1,1,0,1,0,1,0,1,1,0,0,1,1,1,0,1};int choice;system("clear");for(;;){printf("\n 1.ENCODE ");printf("\n 2.DECODE ");printf("\n 3.EXIT ");printf("\n Enter your choice : ");scanf("%d",&choice);switch(choice){case 1:printf("\n Enter 4 data bits\n");scanf("%s",data);for(i=0;i<4;i++){d1[i]=d2[i]=d3[i]=d4[i]=0;p1[i]=p2[i]=p3[i]=1;}

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 54

d1[0]=d2[1]=d3[2]=d4[3]=1;p1[0]=p2[1]=p3[2]=0;for(i=0;i<4;i++)gmatrix[i][0]=p1[i];for(i=0;i<4;i++)gmatrix[i][1]=p2[i];for(i=0;i<4;i++)gmatrix[i][2]=p3[i];for(i=0;i<4;i++)gmatrix[i][3]=d1[i];for(i=0;i<4;i++)gmatrix[i][4]=d2[i];for(i=0;i<4;i++)gmatrix[i][5]=d3[i];for(i=0;i<4;i++)gmatrix[i][6]=d4[i];printf("\n The generator matrix is\n\n");for(i=0;i<4;i++){for(j=0;j<7;j++){printf("%d\t",gmatrix[i][j]);}printf("\n");}for(i=0;i<7;i++)for(j=0;j<4;j++)encode[i]=encode[i] + ( data[j] * gmatrix[j][i]);printf("\n the encoded data is \n");for(i=0;i<7;i++){encode[i]=encode[i] % 2;}for(i=0;i<7;i++)printf("%d",encode[i]);break;case 2:printf("\n enter the encoded data \n");for(i=0;i<7;i++)scanf("%d",&edata[i]);

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 55

for(i=0;i<3;i++)for(j=0;j<7;j++)syn[i]=syn[i] + ( hmatrix[i][j] * edata[j] );for(i=0;i<3;i++)syn[i]=syn[i] % 2;errdig = 4 * syn[0] + 2 * syn[1] + 1 * syn[2];if (errdig == 0)printf("\n Error free data \n");else{printf("\n error in the bit number %d\n",errdig);errdig--;if(edata[errdig] == 1)edata[errdig]=0;elseedata[errdig]=1;}printf("\n the actaual data error free data : ");for(i=3;i<7;i++)printf("%d",edata[i]);break;default : exit(0);}}}

COMPILE AND RUN:-OUTPUT$ cc –o ham ham.c$ ./ham

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 56

Experiment No 8Leaky Bucket

Problem StatementWrite a program for congestion control using Leaky bucket algorithm.

TheoryThe congesting control algorithms are basically divided into two groups: open loop and closed

loop. Open loop solutions attempt to solve the problem by good design, in essence, to make sureit does not occur in the first place. Once the system is up and running, midcourse corrections arenot made. Open loop algorithms are further divided into ones that act at source versus ones thatact at the destination.

In contrast, closed loop solutions are based on the concept of a feedback loop if there is anycongestion. Closed loop algorithms are also divided into two sub categories: explicit feedbackand implicit feedback. In explicit feedback algorithms, packets are sent back from the point ofcongestion to warn the source. In implicit algorithm, the source deduces the existence ofcongestion by making local observation, such as the time needed for acknowledgment to comeback.

The presence of congestion means that the load is (temporarily) greater than the resources (inpart of the system) can handle. For subnets that use virtual circuits internally, these methods canbe used at the network layer.

Another open loop method to help manage congestion is forcing the packet to be transmittedat a more predictable rate. This approach to congestion management is widely used in ATMnetworks and is called traffic shaping.

The other method is the leaky bucket algorithm. Each host is connected to the network by aninterface containing a leaky bucket, that is, a finite internal queue. If a packet arrives at the queuewhen it is full, the packet is discarded. In other words, if one or more process are already queued,the new packet is unceremoniously discarded. This arrangement can be built into the hardwareinterface or simulate d by the host operating system. In fact it is nothing other than a single serverqueuing system with constant service time.

The host is allowed to put one packet per clock tick onto the network. This mechanism turnsan uneven flow of packet from the user process inside the host into an even flow of packet ontothe network, smoothing out bursts and greatly reducing the chances of congestion.

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 57

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 58

Program-Name :Congestion.c#include<stdio.h>int min(int x,int y){if(x<y)return x;elsereturn y;}int main(){int drop=0,mini,nsec,cap,count=0,i,inp[25],process;syste("clear");printf("Enter The Bucket Size\n");scanf("%d",&cap);printf("Enter The Operation Rate\n");scanf("%d",&process);printf("Enter The No. Of Seconds You Want To Stimulate\n");scanf("%d",&nsec);for(i=0;i<nsec;i++){printf("Enter The Size Of The Packet Entering At %dsec\n",i+1);scanf("%d",&inp[i]);}printf("\nSecond|Packet Recieved|Packet Sent|Packet Left|Packet Dropped|\n");printf("--------------------------------------------------------------\n");for(i=0;i<nsec;i++){count+=inp[i];if(count>cap){drop=count-cap;count=cap;}

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 59

printf("%d",i+1);printf("\t%d",inp[i]);mini=min(count,process);printf("\t\t%d",mini);count=count-mini;printf("\t\t%d",count);printf("\t\t%d\n",drop);drop=0;}for(;count!=0;i++){if(count>cap){drop=count-cap;count=cap;}printf("%d",i+1);printf("\t0");mini=min(count,process);printf("\t\t%d",mini);count=count-mini;printf("\t\t%d",count);printf("\t\t%d\n",drop);}}COMPILE AND RUN:-OUTPUT$ cc –o Congestion Congestion.c$ ./CongestionEnter The Bucket Size5Enter The Operation Rate2Enter The No. Of Seconds You Want To Stimulate3Enter The Size Of The Packet Entering At 1 sec5Enter The Size Of The Packet Entering At 1 sec4Enter The Size Of The Packet Entering At 1 sec3

Computer Networks Lab Manual SVCE,BANGALORE-57

Department Of Computer Science and Engineering Page 60

Second | Packet Received | Packet Sent | Packet Left | Packet Dropped|------------------------------------------------------------------------------------1 5 2 3 02 4 2 3 23 3 2 3 14 0 2 1 05 0 1 0