0% found this document useful (0 votes)
139 views195 pages

CN - WT Cse Lab Manual

The document provides an index of experiments for a Computer Networks and Web Technologies lab course. There are 13 listed Computer Networks experiments covering topics like data link layer framing, CRC codes, routing algorithms, and network simulation. There are also 9 Web Technologies experiments involving PHP scripting, XML processing, and converting static web pages to dynamic ones using servlets, JSP, and integrating a database. The document also includes objectives and outcomes for the Computer Networks course portion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views195 pages

CN - WT Cse Lab Manual

The document provides an index of experiments for a Computer Networks and Web Technologies lab course. There are 13 listed Computer Networks experiments covering topics like data link layer framing, CRC codes, routing algorithms, and network simulation. There are also 9 Web Technologies experiments involving PHP scripting, XML processing, and converting static web pages to dynamic ones using servlets, JSP, and integrating a database. The document also includes objectives and outcomes for the Computer Networks course portion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 195

Department of CSE Computer Networks & Web Technologies Lab

COMPUTER NETWORKS and WEB TECHNOLOGIES LAB

B.Tech III YEAR I SEM (R18 JNTUH REGULATIONS)

ACADEMIC YEAR 2021-22

Page no:1
Department of CSE Computer Networks & Web Technologies Lab

INDEX
EXPERIMENT EXPERIMENT NAME PAGE NO.
NO.
Computer Networks lab Experiments
1 Implement the data link layer framing 16
methods such as character, character-
stuffing and bit
stuffing.
2 Write a program to compute CRC code for 20
the polynomials CRC-12, CRC-16 and
CRC CCIP
3 Develop a simple data link layer that 38
performs the flow control using the sliding
window protocol,
and loss recovery using the Go-Back-N
mechanism.
4 Implement Dijsktra’s algorithm to compute 45
the shortest path through a network
5 Take an example subnet of hosts and obtain 47
a broadcast tree for the subnet.
6 Implement distance vector routing 52
algorithm for obtaining routing tables at
each node.
7 Implement data encryption and data 57
decryption
8 Write a program for congestion control 60
using Leaky bucket algorithm.
9 Write a program for frame sorting 63
technique used in buffers.

Page no:2
Department of CSE Computer Networks & Web Technologies Lab

10 Wireshark 67
i. Packet Capture Using Wire shark
ii. Starting Wire shark
iii. Viewing Captured Traffic
iv. Analysis and Statistics & Filters.
11 How to run Nmap scan 74
12 Operating System Detection using Nmap 92
13 Do the following using NS2 Simulator 94
i. NS2 Simulator-Introduction
ii. Simulate to Find the Number of Packets
Dropped
iii. Simulate to Find the Number of Packets
Dropped by TCP/UDP
iv. Simulate to Find the Number of Packets
Dropped due to Congestion
v. Simulate to Compare Data Rate&
Throughput.
vi. Simulate to Plot Congestion for
Different Source/Destination
vii. Simulate to Determine the Performance
with respect to Transmission of Packets
Web Technologies Experiments
1. Write a PHP script to print prime numbers 129
between 1-50.
2. PHP script to 131
a. Find the length of a string.
b. Count no of words in a string.
c. Reverse a string.
d. Search for a specific string.
3. Write a PHP script to merge two arrays and 133
sort them as numbers, in descending order.
4. Write a PHP script that reads data from one 135
file and write into another file.
5. Develop static pages (using Only HTML) 138
of an online book store. The pages should
resemble:
www.amazon.com. The website should
consist the following pages.
a) Home page
b) Registration and user Login
c) User Profile Page
d) Books catalog

Page no:3
Department of CSE Computer Networks & Web Technologies Lab

e) Shopping Cart
f) Payment By credit card
g) Order Conformation
6. Validate the Registration, user login, user 148
profile and payment by credit card pages
using
JavaScript.
7. Create and save an XML document on the 161
server, which contains 10 users
information. Write
a program, which takes User Id as an input
and returns the user details by taking the
user
information from the XML document.
8. Install TOMCAT web server. Convert the 170
static web pages of assignments 2 into
dynamic web
pages using servlets and cookies. Hint:
Users information (user id, password, credit
card
number) would be stored in web.xml. Each
user should have a separate Shopping Cart.
9. Redo the previous task using JSP by 188
converting the static web pages of
assignments 2 into
dynamic web pages. Create a database with
user information and books information.
The
books catalogue should be dynamically
loaded from the database. Follow the MVC
architecture
while doing the website.

Page no:4
Department of CSE Computer Networks & Web Technologies Lab

CS506PC: COMPUTER NETWORKS & WEB TECHNOLOGIES LAB

III Year B.Tech. CSE I-Sem LTPC


3003

Computer Networks Course Objectives

1. To understand the working principle of various communication protocols.


2. To understand the network simulator environment and visualize a network
topology and observe its performance
3. To analyze the traffic flow and the contents of protocol frames

Computer Networks Course Outcomes

1. Implement data link layer farming methods


2. Analyze error detection and error correction codes.
3. Implement and analyze routing and congestion issues in network design.
4. Implement Encoding and Decoding techniques used in presentation layer
5. To be able to work with different network tools

CO-PO-PSO Matrix

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2

CO1 2

CO2 1 2 1 1

CO3 1 1 2

CO4 2 1 2 2 1

CO5 2 2 1 1 1

KMIT Page no:5


Department of CSE Computer Networks & Web Technologies Lab

Computer Networks List of Experiments

1. Implement the data link layer framing methods such as character, character-
stuffing and bit stuffing.

2. Write a program to compute CRC code for the polynomials CRC-12, CRC-
16 and CRC CCIP.
3. Develop a simple data link layer that performs the flow control using the
sliding window protocol, and loss recovery using the Go-Back-N mechanism.

4. Implement Dijsktra’s algorithm to compute the shortest path through a


network
5. Take an example subnet of hosts and obtain a broadcast tree for the subnet.
6. Implement distance vector routing algorithm for obtaining routing tables at
each node.
7. Implement data encryption and data decryption
8. Write a program for congestion control using Leaky bucket algorithm.
9. Write a program for frame sorting technique used in buffers.

10. Wireshark
i. Packet Capture Using Wire shark
ii. Starting Wire shark
iii. Viewing Captured Traffic
iv. Analysis and Statistics & Filters.
11. How to run Nmap scan
12. Operating System Detection using Nmap
13. Do the following using NS2 Simulator
i. NS2 Simulator-Introduction
ii. Simulate to Find the Number of Packets Dropped
iii. Simulate to Find the Number of Packets Dropped by TCP/UDP
iv. Simulate to Find the Number of Packets Dropped due to Congestion
v. Simulate to Compare Data Rate& Throughput.
vi. Simulate to Plot Congestion for Different Source/Destination

KMIT Page no:6


Department of CSE Computer Networks & Web Technologies Lab

vii. Simulate to Determine the Performance with respect to Transmission of


Packets.
Web Technologies Course Objectives:
1. To introduce PHP language for server-side scripting
2. To introduce XML and processing of XML Data with Java
3. To introduce Server-side programming with Java Servlets and JSP
4. To introduce Client-side scripting with Javascript and AJAX.
Web Technologies Course Outcomes
1. Gain knowledge of client-side scripting, validation of forms and AJAX
programming
2. Understand server-side scripting with PHP language
3. Understand what XML is and how to parse and use XML Data with Java
4. To introduce Server-side programming with Java Servlets and JSP

CO-PO-PSO Matrix:

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2

CO1 3 3 2 2 2 2 2 3 2

CO2 3 2 2 3 3 3 3 3 2

CO3 3 2 3 2 2 2 2 2 3

CO4 3 3 3 3 3 3 3 3 2

KMIT Page no:7


Department of CSE Computer Networks & Web Technologies Lab

Web Technologies Experiments

1. Write a PHP script to print prime numbers between 1-50.

2. PHP script to
a. Find the length of a string.
b. Count no of words in a string.
c. Reverse a string.
d. Search for a specific string.
3. Write a PHP script to merge two arrays and sort them as numbers, in
descending order.

4. Write a PHP script that reads data from one file and write into another
file.

5. Develop static pages (using Only HTML) of an online book store. The
pages should resemble:www.amazon.com. The website should consist the
following pages.

a) Home page
b) Registration and user Login
c) User Profile Page
d) Books catalog
e) Shopping Cart
f) Payment By credit card
g) Order Conformation

6. Validate the Registration, user login, user profile and payment by credit
card pages usingJavaScript.

7. Create and save an XML document on the server, which contains 10 users
information. Write a program, which takes User Id as an input and returns
the user details by taking the user information from the XML document.

8. Install TOMCAT web server. Convert the static web pages of assignments
2 into dynamic web pages using servlets and cookies. Hint: Users
information (user id, password, credit card number) would be stored in
web.xml. Each user should have a separate Shopping Cart.

KMIT Page no:8


Department of CSE Computer Networks & Web Technologies Lab

9. Redo the previous task using JSP by converting the static web pages of
assignments 2 into dynamic web pages. Create a database with user
information and books information. The books catalogue should be
dynamically loaded from the database. Follow the MVC architecture
while doing the website.

KMIT Page no:9


Department of CSE Computer Networks & Web Technologies Lab

Implement the data link layer framing method such as bit stuffing.
AIM:

Program:
#include <stdio.h>
#include <conio.h>
main()
{
char a[20],fs[50]="",t[6],r[5];
int i,j,p=0,q=0;
clrscr();
printf("enter bit string : ");
scanf("%s",a);
strcat(fs,"01111110");

if(strlen(a)<5)
{
strcat(fs,a);
}
else
{
for(i=0;i<strlen(a)-4;i++)
{
for(j=i;j<i+5;j++)
{
t[p++]=a[j];
}
t[p]='\0';
if(strcmp(t,"11111")==0)
{
strcat(fs,"111110");
i=j-1;
}
else
{
r[0]=a[i];
r[1]='\0';
strcat(fs,r);
}
p=0;
}
for(q=i;q<strlen(a);q++)
{

KMIT Page no:10


Department of CSE Computer Networks & Web Technologies Lab

t[p++]=a[q];
}
t[p]='\0';
strcat(fs,t);
}
strcat(fs,"01111110");
printf("After stuffing : %s",fs);

getch();
}
Output:
Enter bit string: 10101111110

After stuffing: 0111111010101111101001111110

Enter bit string: 1011111011110111110

After stuffing: 0111111010111110011110111110001111110

KMIT Page no:11


Department of CSE Computer Networks & Web Technologies Lab

Implement the data link layer framing method such as Character Stuffing
AIM:
Program :
#include<stdio.h>
#include<string.h>
void main()
{
char a[30],fs[50]=" ",t[3],sd,ed,x[3],s[3],d[3],y[3];
int i,j,p=0,q=0;
printf("Enter characters to be stuffed:");
scanf("%s",a);
printf("\nEnter a character that represents starting delimiter:");
scanf(“ “);
scanf("%c",&sd);
printf("\nEnter a character that represents ending delimiter:");
scanf(“ “);
scanf("%c",&ed);
x[0]=s[0]=s[1]=sd; x[1]=s[2]='\0';
y[0]=d[0]=d[1]=ed; d[2]=y[1]='\0';
strcat(fs,x);
for(i=0;i<strlen(a);i++)
{
t[0]=a[i];
t[1]='\0';
if(t[0]==sd)
strcat(fs,s);
else if(t[0]==ed)
strcat(fs,d);
else

KMIT Page no:12


Department of CSE Computer Networks & Web Technologies Lab

strcat(fs,t);
}
strcat(fs,y);
printf("\n After stuffing:%s",fs);
}
OUTPUT:
Enter characters to be stuffed: goodday
Enter a character that represents starting delimiter: d
Enter a character that represents ending delimiter: g
After stuffing: dggooddddayg.

KMIT Page no:13


Department of CSE Computer Networks & Web Technologies Lab

Implement on a data set of characters the CRC .


AIM:
Program:
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
void main()
{
int i,j,n,g,a,arr[20],gen[20],b[20],q[20],s;
clrscr();
printf("Transmitter side:");
printf("\nEnter no. of data bits:");
scanf("%d",&n);
printf("Enter data:");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("Enter size of generator:");
scanf("%d",&g);
do{
printf("Enter generator:");
for(j=0;j<g;j++)
scanf("%d",&gen[j]);
}
while(gen[0]!=1);
printf("\n\tThe generator matrix:");
for(j=0;j<g;j++)
printf("%d",gen[j]);
a=n+(g-1);
printf("\n\tThe appended matrix is:");

KMIT Page no:14


Department of CSE Computer Networks & Web Technologies Lab

for(i=0;i< j;++i)
arr[n+i]=0;
for(i=0;i< a;++i)
printf("%d",arr[i]);
for(i=0;i< n;++i)
q[i]= arr[i];
for(i=0;i< n;++i)
{
if(arr[i]==0)
{
for(j=i;j<g+i;++j)
arr[j] = arr[j]^0;
}
else
{
arr[i] = arr[i]^gen[0];
arr[i+1]=arr[i+1]^gen[1];
arr[i+2]=arr[i+2]^gen[2];
arr[i+3]=arr[i+3]^gen[3];
}}
printf("\n\tThe CRC is :");
for(i=n;i< a;++i)
printf("%d",arr[i]);
s=n+a;
for(i=n;i<s;i++)
q[i]=arr[i];
printf("\n");
for(i=0;i<a;i++)
printf("%d",q[i]);
getch();

KMIT Page no:15


Department of CSE Computer Networks & Web Technologies Lab

Output:

Transmitter side:
Enter no. of data bits:8
Enter data:1 0 1 0 0 0 0 1
Enter size of generator:4
Enter generator:1 0 0 1
The generator matrix:1001
The appended matrix is:10100001000
The CRC is :111
10100001111

KMIT Page no:16


Department of CSE Computer Networks & Web Technologies Lab

Implement CRC 12 bit


AIM:
Program:
#include<stdio.h>
const char * bindiv(const char *,const char *);
const char * binsub(const char *,const char *);
int f=0,ll=0;
void main()
{
char *a,p[13]="1100000001011",g[30],g1[30],yy[30]="",td[30],*aa;
int l=0,i;
clrscr();
printf("Enter transfered data : ");
scanf("%s",g);
printf("Enter received data : ");
scanf("%s",td);
strcpy(g1,g);
strcat(g,"000000000000");
printf("\n%s ) %s (",p,g);
a=bindiv(g,p);
if(strlen(a)<12)
{
for(i=strlen(a);i<12;i++)
{
yy[l++]='0';
}
yy[l]='\0';
}
strcat(yy,a);
strcat(g1,yy);

KMIT Page no:17


Department of CSE Computer Networks & Web Technologies Lab

printf("\ncrc is %s",yy);
printf("\n ----------------------------- ");
strcat(td,yy);
printf("\n\n%s ) %s (",p,td);
ll=0;
aa=bindiv(td,p);
strcpy(a,aa);
printf("\n %s",a);
printf("\n ---------------------------- ");
if(f==1)
printf("\nDatatransfered correctly");
else
printf("\nDatatransfered incorrectly");
getch();
}
const char * bindiv(const char *s,const char *d)
{
int i,j,k=0,x=13,h,p=0,l;
char q[15]="",b[30],*w;
for(i=0;i<strlen(s);i++)
{
if((i+x)>strlen(s))
x=(i+x)-strlen(s)+1;
for(j=i;j<(i+x);j++)
{ b[k++]=s[j]; }
b[k]='\0';
if(ll!=0)
printf("\n %s",b);
ll=1;
if(strlen(b)==12)

KMIT Page no:18


Department of CSE Computer Networks & Web Technologies Lab

{
break;
}
printf("\n %s",d);
printf("\n ---------------------------- ");
w=binsub(b,d);
k=0;i=j-1;
for(l=0;l<strlen(w);l++)
{
if(w[l]=='1')
break;
}
if(l==strlen(w))
{
f=1;
return(w);
}
for(h=l;h<strlen(w);h++)
{
q[p++]=w[h];
}
q[p]='\0';
x=13-strlen(q);
strcpy(b,"");
strcat(b,q);
k=strlen(q); p=0;
}
return(b);
}
const char * binsub(const char *x,const char *y)

KMIT Page no:19


Department of CSE Computer Networks & Web Technologies Lab

{
int i,j=0;
char w[15]="",e[3],f[3],n[3];
e[0]='1';
e[1]='\0';
f[0]='0';
f[1]='\0';
for(i=0;i<strlen(x);i++)
{
if((x[i]=='1')&&(y[i]=='1'))
strcat(w,f);
else
if((x[i]=='0')&&(y[i]=='0'))
strcat(w,f);
else
strcat(w,e);
}
n[0]='\0';
n[1]='\0';
strcat(w,n);
return(w);
}
Output:
Enter transferred data: 11011 , Enter received data: 11011
10001000000100001 ) 110110000000000000000 (
10001000000100001

10100000001000010
10001000000100001

KMIT Page no:20


Department of CSE Computer Networks & Web Technologies Lab

10100000110001100
10001000000100001

1010001101011010

crc is 1010001101011010
10001000000100001 ) 110111010001101011010 (
10001000000100001

10101010000101001
10001000000100001

10001000000100001
10001000000100001

00000000000000000
-------------------------- Data transferred correctly

KMIT Page no:21


Department of CSE Computer Networks & Web Technologies Lab

2.C. Implement on a data set of characters the CRC Polynomial CRC 16


AIM:
Program:
#include<stdio.h>
const char * bindiv(const char *,const char *);
const char * binsub(const char *,const char *);
int f=0,ll=0;
void main()
{
char *a,p[20]="10001000000100001",
g[30],g1[30],yy[30]="",td[30],*aa;
int l=0,i;
clrscr();
printf("Enter transfered data: ");
scanf("%s",g);
printf("Enter received data: ");
scanf("%s",td);
strcpy(g1,g);
strcat(g,"0000000000000000");
printf("\n%s ) %s (",p,g);
a=bindiv(g,p);
if(strlen(a)<16)
{
for(i=strlen(a);i<16;i++)
{
yy[l++]='0';
}
yy[l]='\0';
}

KMIT Page no:22


Department of CSE Computer Networks & Web Technologies Lab

strcat(yy,a);
strcat(g1,yy);
printf("\n --------------------------------");
printf("\ncrc is %s",yy);
strcat(td,yy);
printf("\n\n%s ) %s (",p,td);
ll=0;
aa=bindiv(td,p);
strcpy(a,aa);
printf("\n %s",a);
printf("\n -------------------------------");
if(f==1)
printf("\nDatatransfered correctly");
else
printf("\nDatatransfered incorrectly");
getch();
}
const char * bindiv(const char *s,const char *d)
{
int i,j,k=0,x=17,h,p=0,l;
char q[25]="",b[30],*w;
for(i=0;i<strlen(s);i++)
{
if((i+x)>strlen(s))
x=(i+x)-strlen(s)+1;
for(j=i;j<(i+x);j++)
{
b[k++]=s[j];
}
b[k]='\0';

KMIT Page no:23


Department of CSE Computer Networks & Web Technologies Lab

if(ll!=0)
printf("\n %s",b);
ll=1;
if(strlen(b)==16)
{
break;
}
printf("\n %s",d);
printf("\n ------------------- ");
w=binsub(b,d);
k=0;i=j-1;
for(l=0;l<strlen(w);l++)
{
if(w[l]=='1')
break;
}
if(l==strlen(w))
{
f=1;
return(w);
}
for(h=l;h<strlen(w);h++)
{
q[p++]=w[h];
}
q[p]='\0';
x=17-strlen(q);
strcpy(b,"");
strcat(b,q);
k=strlen(q); p=0;

KMIT Page no:24


Department of CSE Computer Networks & Web Technologies Lab

}
return(b);
}
const char * binsub(const char *x,const char *y)
{
int i,j=0;
char w[25]="",e[3],f[3],n[3];
e[0]='1';
e[1]='\0';
f[0]='0';
f[1]='\0';
for(i=0;i<strlen(x);i++)
{
if((x[i]=='1')&&(y[i]=='1'))
strcat(w,f);
else
if((x[i]=='0')&&(y[i]=='0'))
strcat(w,f);
else
strcat(w,e);
}
n[0]='\0';
n[1]='\0';
strcat(w,n); return(w);
}

KMIT Page no:25


Department of CSE Computer Networks & Web Technologies Lab

Output:
Enter transferred data: 11011 , Enter received data: 11011
10001000000100001) 110110000000000000000 (
10001000000100001

10100000001000010
10001000000100001

10100000110001100
10001000000100001

1010001101011010

crc is 1010001101011010
10001000000100001) 110111010001101011010 (
10001000000100001

10101010000101001
10001000000100001

10001000000100001
10001000000100001

00000000000000000
-------------------------- Data transferred correctly

2.D.Implement program for CRC-CCITT


AIM:
Program:
#include<stdio.h>

KMIT Page no:26


Department of CSE Computer Networks & Web Technologies Lab

const char * bindiv(const char *,const char *);


const char * binsub(const char *,const char *);
int f=0,ll=0;
void main()
{
char *a,p[20]="10001000000100001 ",
g[30],g1[30],yy[30]="",td[30],*aa;
int l=0,i;
clrscr();
printf("Enter transfered data: ");
scanf("%s",g);
printf("Enter received data: ");
scanf("%s",td);
strcpy(g1,g);
strcat(g,"0000000000000000");
printf("\n%s ) %s (",p,g);
a=bindiv(g,p);
if(strlen(a)<16)
{
for(i=strlen(a);i<16;i++)
{
yy[l++]='0';
}
yy[l]='\0';
}
strcat(yy,a);
strcat(g1,yy);
printf("\n --------------------------------");
printf("\ncrc is %s",yy);
strcat(td,yy);

KMIT Page no:27


Department of CSE Computer Networks & Web Technologies Lab

printf("\n\n%s ) %s (",p,td);
ll=0;
aa=bindiv(td,p);
strcpy(a,aa);
printf("\n %s",a);
printf("\n -------------------------------");
if(f==1)
printf("\nDatatransfered correctly");
else
printf("\nDatatransfered incorrectly");
getch();
}
const char * bindiv(const char *s,const char *d)
{
int i,j,k=0,x=17,h,p=0,l;
char q[25]="",b[30],*w;
for(i=0;i<strlen(s);i++)
{
if((i+x)>strlen(s))
x=(i+x)-strlen(s)+1;
for(j=i;j<(i+x);j++)
{
b[k++]=s[j];
}
b[k]='\0';
if(ll!=0)
printf("\n %s",b);
ll=1;
if(strlen(b)==16)
{

KMIT Page no:28


Department of CSE Computer Networks & Web Technologies Lab

break;
}
printf("\n %s",d);
printf("\n ");
w=binsub(b,d);
k=0;i=j-1;
for(l=0;l<strlen(w);l++)
{
if(w[l]=='1')
break;
}
if(l==strlen(w))
{
f=1;
return(w);
}
for(h=l;h<strlen(w);h++)
{
q[p++]=w[h];
}
q[p]='\0';
x=17-strlen(q);
strcpy(b,"");
strcat(b,q);
k=strlen(q); p=0;
}
return(b);
}
const char * binsub(const char *x,const char *y)
{

KMIT Page no:29


Department of CSE Computer Networks & Web Technologies Lab

int i,j=0;
char w[25]="",e[3],f[3],n[3];
e[0]='1';
e[1]='\0';
f[0]='0';
f[1]='\0';
for(i=0;i<strlen(x);i++)
{
if((x[i]=='1')&&(y[i]=='1'))
strcat(w,f);
else
if((x[i]=='0')&&(y[i]=='0'))
strcat(w,f);
else
strcat(w,e);
}
n[0]='\0';
n[1]='\0';
strcat(w,n);
return(w);
}
Output:
Enter transferred data: 11011 , Enter received data: 11011
10001000000100001) 110110000000000000000 (
10001000000100001

10100000001000010
10001000000100001

10100000110001100

KMIT Page no:30


Department of CSE Computer Networks & Web Technologies Lab

10001000000100001

1010001101011010

crc is 1010001101011010
10001000000100001) 110111010001101011010 (
10001000000100001

10101010000101001
10001000000100001

10001000000100001
10001000000100001

00000000000000000
-------------------------- Data transferred correctly

KMIT Page no:31


Department of CSE Computer Networks & Web Technologies Lab

Develop a simple data link layer that performs the flow control using the sliding
window protocol

AIM:
Program:
#include<stdio.h>
int main()
{
int w,i,f,frames[50];
printf("Enter window size: ");
scanf("%d",&w);
printf("\nEnter number of frames to transmit: ");
scanf("%d",&f);
printf("\nEnter %d frames: ",f);
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);
printf("\nWith sliding window protocol the frames will be sent in the following manner
(assuming no corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for acknowledgement sent by the
receiver\n\n",w);
for(i=1;i<=f;i++)
{
if(i%w==0)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by sender\n\n");
} else
printf("%d ",frames[i]);
}
if(f%w!=0)
printf("\nAcknowledgement of above frames sent is received by sender\n");

KMIT Page no:32


Department of CSE Computer Networks & Web Technologies Lab

return 0; }

Output:
Enter window size: 3
Enter number of frames to transmit: 5
Enter 5 frames: 12 5 89 4 6
With sliding window protocol the frames will be sent in the following manner (assuming no
corruption of frames)
After sending 3 frames at each stage sender waits for acknowledgement sent by the receiver
12 5 89
Acknowledgement of above frames sent is received by sender
46
Acknowledgement of above frames sent is received by sender

KMIT Page no:33


Department of CSE Computer Networks & Web Technologies Lab

Develop a simple data link layer that performs the flow control using the Go Back N
protocol in c

AIM:

Program:
#include<stdio.h>
int main()
{
int windowsize,sent=0,ack,i;
printf("enter window size\n");
scanf("%d",&windowsize);
while(1)
{
for( i = 0; i<windowsize; i++)
{
printf("Frame %d has been transmitted.\n",sent);
sent++;
if(sent == windowsize)
break;
}
printf("\nPlease enter the last Acknowledgement received.\n");
scanf("%d",&ack);
if(ack == windowsize)
break;
else
sent = ack;
}
return 0;
}

KMIT Page no:34


Department of CSE Computer Networks & Web Technologies Lab

Output:
enter window size
8
Frame 0 has been transmitted.
Frame 1 has been transmitted.
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.
Please enter the last Acknowledgement received.
2
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received.


8

KMIT Page no:35


Department of CSE Computer Networks & Web Technologies Lab

Develop a simple data link layer that performs the flow control using the Go Back N
protocol in c++

AIM:

Program:
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
int nf,N;
int no_tr=0;
srand(time(NULL));
cout<<"Enter the number of frames : ";
cin>>nf;
cout<<"Enter the Window Size : ";
cin>>N;
int i=1;
while(i<=nf)
{
int x=0;
for(int j=i;j<i+N&& j<=nf;j++)
{
cout<<"Sent Frame "<<j<<endl;
no_tr++;
}
for(int j=i;j<i+N&& j<=nf;j++)
{
int flag = rand()%2;
if(!flag)

KMIT Page no:36


Department of CSE Computer Networks & Web Technologies Lab

{
cout<<"Acknowledgment for Frame "<<j<<endl;
x++;
}
else
{ cout<<"Frame "<<j<<" Not Received"<<endl;
cout<<"Retransmitting Window"<<endl;
break;
}
}
cout<<endl;
i+=x;
}
cout<<"Total number of transmissions : "<<no_tr<<endl;
return 0;
}
Output:
Enter the number of frames: 10
Enter the Window Size : 3
Sent Frame 1
Sent Frame 2
Sent Frame 3
Acknowledgment for Frame 1
Acknowledgment for Frame 2
Acknowledgment for Frame 3
Sent Frame 4
Sent Frame 5
Sent Frame 6
Frame 4 Not Received
Retransmitting Window
KMIT Page no:37
Department of CSE Computer Networks & Web Technologies Lab

Sent Frame 4
Sent Frame 5
Sent Frame 6
Acknowledgment for Frame 4
Acknowledgment for Frame 5
Acknowledgment for Frame 6

Sent Frame 7
Sent Frame 8
Sent Frame 9
Acknowledgment for Frame 7
Acknowledgment for Frame 8
Acknowledgment for Frame 9

Sent Frame 10
Acknowledgment for Frame 10
Total number of transmissions: 13

KMIT Page no:38


Department of CSE Computer Networks & Web Technologies Lab

4. Implement Dijkstra’s algorithm to compute the shortest path through a graph.


AIM:

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int path[5][5],i,j,min,a[5][5],p,st=1,ed=5,stp,edp,t[5],index;
clrscr();
printf("enter the cost matrix\n");
for(i=1;i<=5;i++)
for(j=1;j<=5;j++)
scanf("%d",&a[i][j]);
printf("enter number of paths\n");
scanf("%d",&p);
printf("enter possible paths\n");
for(i=1;i<=p;i++)
for(j=1;j<=5;j++)
scanf("%d",&path[i][j]);
for(i=1;i<=p;i++)
{
t[i]=0;
stp=st;
for(j=1;j<=5;j++)
{
edp=path[i][j+1];
t[i]=t[i]+a[stp][edp];
if(edp==ed)
break;
else
stp=edp;
}
}
min=t[st];index=st;
for(i=1;i<=p;i++)
{
if(min>t[i])
{
min=t[i];
index=i;
}
}
printf("minimum cost %d",min);
printf("\n minimum cost path ");

KMIT Page no:39


Department of CSE Computer Networks & Web Technologies Lab

for(i=1;i<=5;i++)
{
printf("--> %d",path[index][i]);
if(path[index][i]==ed)
break;
} getch(); }

Output:

enter the cost matrix :


01420
00023
00030
00005
00000
enter number of paths : 4
enter possible paths :
12450
12500
14500
13450
minimum cost : 4
minimum cost path :
1-->2-->5

KMIT Page no:40


Department of CSE Computer Networks & Web Technologies Lab

5.Take an example subnet of hosts and obtain a broadcast tree for the subnet.
AIM:
Program:
#include <stdio.h>
int max();
int distance[20];
int n;

main()
{
int adj[20][20],adj1[20][20],flag[30];
int i,j,root,x;
int source,count=1,y=0;
printf("enter no of nodes");
scanf("%d",&n);

for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&adj[i][j]);
}
}

printf("enter the source for broadcasting");


scanf("%d",&source);

for(i=0;i<n;i++)
{
flag[i]=0;
}

for(root=0;root<n;root++)
{
for(i=0;i<N;I++)
{
distance[i]=adj[root][i];
}
x=min();

for(i=0;i<n;i++)
{

if(distance[i]==x)
{

KMIT Page no:41


Department of CSE Computer Networks & Web Technologies Lab

adj1[root][i]=x;
adj1[i][root]=x;
}
else
{
adj1[root][i]=0;
}
}
}

for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(adj1[i][j]!=0)
{
adj1[j][i]=adj[i][j];
}
}
}

printf("given adjacency matrix is");

for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d",adj[i][j]);
}
printf("\n");
}
printf("minimal spanning tree");

for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",adj1[i][j]);
}
printf("\n");
}
root=source;
flag[root]=1;
while(count!=y)
{
for(i=0;i<n;i++)

KMIT Page no:42


Department of CSE Computer Networks & Web Technologies Lab

{
if(adj1[root][i]!=0 && flag[root]==1 && flag[i]!=1)
{
printf("%d sends message to %d \n",root,i);
flag[i]=1;
}
}
if(root<n-1)
{
root++;
}
else
{
root=0;
}
for(i=0;i<n;i++)
{
if(flag[i]==0)
{
break;
}
}
if(i==n)
{
count=y;
}
}
}

int min()
{
int i,j=0;
int mini;
int distance1[10];
for(i=0;i<n;i++)
{
if(distance[i]!=0)
{
distance1[j]=distance[i];
j++;
}
}
mini=distance1[0];

for(i=1;i<j;i++)
{

KMIT Page no:43


Department of CSE Computer Networks & Web Technologies Lab

if(distance1[i]<mini)
{
mini=distance1[i];
}
}
return(mini);
}
Output:
enter no of nodes2
enter the adjacency matrix
02
20
enter the source for broadcasting1
given adjacency matrix is
02
20

minimal spanning tree is


02
20
1 sends message to 0

enter no of nodes3
enter the adjacency matrix
012
105
250
enter the source for broadcasting2
given adjacency matrix is
012
105
250

25

minimal spanning tree is


012
100
200

1
2

KMIT Page no:44


Department of CSE Computer Networks & Web Technologies Lab

2 sends message to 0
0 sends message to 1

enter no of nodes4
enter the adjacency matrix
0687
6050
8504
7040
enter the source for broadcasting2

given adjacency matrix is


0687
6050
8504
7040

785

minimal spanning tree is


0600
6050
0504
0040

2 sends message to 1
2 sends message to 3
1 sends message to 0

KMIT Page no:45


Department of CSE Computer Networks & Web Technologies Lab

6. Implement distance vector routing algorithm for obtaining routing tables at each node.
AIM:
Program:
#include <stdio.h>
int ja,ji,jh,jk;
void calc( );
int repa[20],repi[20],reph[20],repk[20],rsp[20];
char line[20];
int main( )
{
int i=0;
printf("Enter a delay time\n");
scanf("%d %d %d %d",&ja,&ji,&jh,&jk);
printf("Enter response time\n");
for(i=0;i<12;i++)
{
printf("Enter value \n");
scanf("%d %d %d %d",&repa[i],&repi[i],&reph[i],&repk[i]);
}
calc( );
printf("Least response\n");
for(i=0;i<12;i++)
{
printf("%d\t%c\n",rsp[i],line[i]);
}}
void calc( )
{
int i;
for(i=0;i<12;i++)
{

KMIT Page no:46


Department of CSE Computer Networks & Web Technologies Lab

repa[i]=repa[i]+ja;
repi[i]=repi[i]+ji;
reph[i]=reph[i]+jh;
repk[i]=repk[i]+jk;
}
for(i=0;i<12;i++)
{
if(i==9)
{
rsp[i]=0;
line[i]='J';
}
else
{
rsp[i]=min(repa[i],repi[i],reph[i],repk[i]);
if(rsp[i]==repa[i])
line[i]='A';
else if(rsp[i]==repi[i])
line[i]='I';
else if(rsp[i]==reph[i])
line[i]='H';
else
line[i]='K';
}
}
}
int min(int repa,intrepi,intreph,intrepk)
{
int i,j;
if(repa<repi)

KMIT Page no:47


Department of CSE Computer Networks & Web Technologies Lab

i=repa;
else
i=repi;
if(reph<repk)
j=reph;
else
j=reph;
if(i<j)
return i;
else
return j;
}
Output:
Enter a delay time
8
10
12
6
Enter response time
Enter value
0
24
20
21
Enter value
12
36
31
28
Enter value
25
18
19
36
Enter value
40
27
8
24

KMIT Page no:48


Department of CSE Computer Networks & Web Technologies Lab

Enter value
14
7
30
22
Enter value
23
20
19
40
Enter value
18
31
6
31
Enter value
17
20
0
19
Enter value
21
0
14
22
Enter value
9
11
7
10
Enter value
24
22
22
0
Enter value
29
33
9
9
Least response
8 A
20 A
28 I
20 H
17 I

KMIT Page no:49


Department of CSE Computer Networks & Web Technologies Lab

30 I
18 H
12 H
10 I
J
32 A
21 H

KMIT Page no:50


Department of CSE Computer Networks & Web Technologies Lab

7. Implementation of data encryption and decryption.


AIM:

Program:
Program to implement RSA(Asymmetric Key algorithm)
#include<stdio.h>
#include<string.h>
#include<math.h>
void main( )
{ int n,i,s,n2,k1,p,q,d,m1,e1,l5,z,p2[30],s1,c[30];
unsigned long int l3,m,l4,k2;
double l2,l1,l6;
float e,l;
char p1[30];
clrscr();
printf(“Enter two prime numbers p and q \n”);
scanf(“%d%d”,&p,&q);
n=p*q;
z=((p-1)*(q-1));
printf(“Enter the value of d:\n”);
scanf(“%d”,&d);
l=l*(abs(z));
e=ceil(l/d);
printf(“%d%d%f\n”,n,z,e);
printf(“ENCRYPTION-CIPHER TEXT”);
printf(“Enter the plaintext\n”);
scanf(“%s”,p1);
for(i=0;i<strlen(p1);i++)
{
s=p1[I]-64;

KMIT Page no:51


Department of CSE Computer Networks & Web Technologies Lab

printf(“%d”,s);
e1=(int)e;
l1=pow(((double)s),((double)e1));
l4=(unsigned long int)l1;
k2=l4%n;
c[i]=(int)k2;
printf(“cipher:%d\n”,c[i]);
}
printf(“\n”);
for(i=0;i<strlen(p1);i++)
{
l2=(pow(((double)c[i]),((double)d)));
l5=(int)(l2/n);
l6=l5*33;
m=l2-l6;
m1=(int)m;
k1=m1+64;
printf(“%c\n”,k1);
}
getch( );
}
Output:
Enter two prime numbers p and q
3 11
Enter the value of d:
7
33 20 3.000000
ENCRYPTION CIPHER TEXT
Enter the plain text
SUZANNE
KMIT Page no:52
Department of CSE Computer Networks & Web Technologies Lab

19cipher:28
21cipher:21
26cipher:20
1cipher:1
14cipher:5
14cipher:5
5cipher:26
S
U
Z
A
N
N
E

KMIT Page no:53


Department of CSE Computer Networks & Web Technologies Lab

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


AIM:
Program:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

#define NOF_PACKETS 10

int rand(int a)
{
int rn = (random() % 10) % a;
returnrn == 0 ? 1 :rn;
}

int main()
{
intpacket_sz[NOF_PACKETS], i, clk, b_size, o_rate, p_sz_rm=0, p_sz, p_time, op;
for(i = 0; i<NOF_PACKETS; ++i)
packet_sz[i] = rand(6) * 10;
for(i = 0; i<NOF_PACKETS; ++i)
printf("\npacket[%d]:%d bytes\t", i, packet_sz[i]);
printf("\nEnter the Output rate:");
scanf("%d", &o_rate);
printf("Enter the Bucket Size:");
scanf("%d", &b_size);
for(i = 0; i<NOF_PACKETS; ++i)
{
if( (packet_sz[i] + p_sz_rm) >b_size)
if(packet_sz[i] >b_size)/*compare the packet siz with bucket size*/
printf("\n\nIncoming packet size (%dbytes) is Greater than bucket capacity (%dbytes)-PACKET
REJECTED", packet_sz[i], b_size);
else
printf("\n\nBucket capacity exceeded-PACKETS REJECTED!!");
else
{
p_sz_rm += packet_sz[i];
printf("\n\nIncoming Packet size: %d", packet_sz[i]);
printf("\nBytes remaining to Transmit: %d", p_sz_rm);
p_time = rand(4) * 10;
printf("\nTime left for transmission: %d units", p_time);
for(clk = 10; clk<= p_time; clk += 10)
{

KMIT Page no:54


Department of CSE Computer Networks & Web Technologies Lab

sleep(1);
if(p_sz_rm)
{
if(p_sz_rm<= o_rate)/*packet size remaining comparing with output rate*/
op = p_sz_rm, p_sz_rm = 0;
else
op = o_rate, p_sz_rm -= o_rate;
printf("\nPacket of size %d Transmitted", op);
printf(" --- Bytes Remaining to Transmit: %d", p_sz_rm);
}
else
{
printf("\nTime left for transmission: %d units", p_time-clk);
printf("\nNo packets to transmit!!");
}
}
}
}
}

Output:

KMIT Page no:55


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:56


Department of CSE Computer Networks & Web Technologies Lab

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


AIM:
Program for frame sorting:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define FSize 3
typedef struct packet{int SeqNum; char Data[FSize+1];}packet;
struct packet *readdata, *transdata;
int divide(char *msg) {
int msglen, NoOfPacket, i, j;
msglen = strlen(msg);
NoOfPacket = msglen/FSize;
if ((msglen%FSize)!=0) NoOfPacket++;
readdata = (struct packet *)malloc(sizeof(packet) * NoOfPacket);
for(i = 0; i<NoOfPacket; i++) {
readdata[i].SeqNum = i + 1;
for (j = 0; (j <FSize) && (*msg != '\0'); j++, msg++)
readdata[i].Data[j] = *msg;
readdata[i].Data[j] = '\0';
}
printf("\nThe Message has been divided as follows\n");
printf("\nPacket No. Data\n\n");
for (i = 0; i<NoOfPacket; i++)
printf(" %2d %s\n", readdata[i].SeqNum,
readdata[i].Data);
return NoOfPacket;

KMIT Page no:57


Department of CSE Computer Networks & Web Technologies Lab

}
void shuffle(int NoOfPacket) {
int *Status;
int i, j, trans;
randomize();
Status=(int * )calloc(NoOfPacket, sizeof(int));
transdata = (struct packet *)malloc(sizeof(packet) * NoOfPacket);
for (i = 0; i<NoOfPacket;) {
trans = rand()%NoOfPacket;
if (Status[trans]!=1) {
transdata[i].SeqNum = readdata[trans].SeqNum;
strcpy(transdata[i].Data, readdata[trans].Data);
i++; Status[trans] = 1;
}
}
free(Status);
}
void sortframes(int NoOfPacket) {
packet temp;
int i, j;
for (i = 0; i<NoOfPacket; i++)
for (j = 0; j <NoOfPacket – i-1; j++)
if (transdata[j].SeqNum>transdata[j + 1].SeqNum) {
temp.SeqNum = transdata[j].SeqNum;
strcpy(temp.Data, transdata[j].Data);
transdata[j].SeqNum = transdata[j + 1].SeqNum;
strcpy(transdata[j].Data, transdata[j + 1].Data);
transdata[j + 1].SeqNum = temp.SeqNum;
strcpy(transdata[j + 1].Data, temp.Data);
}}

KMIT Page no:58


Department of CSE Computer Networks & Web Technologies Lab

void receive(int NoOfPacket) {


int i;
printf("\nPackets received in the following order\n");
for (i = 0; i<NoOfPacket; i++) printf("%4d", transdata[i].SeqNum);
sortframes(NoOfPacket);
printf("\n\nPackets in order after sorting..\n");
for (i = 0; i<NoOfPacket; i++) printf("%4d", transdata[i].SeqNum);
printf("\n\nMessage received is :\n");
for (i = 0; i<NoOfPacket; i++) printf("%s", transdata[i].Data);
}
void main() {
char *msg;
int NoOfPacket;
clrscr();
printf("\nEnter The message to be Transmitted :\n");
scanf("%[^\n]", msg);
NoOfPacket = divide(msg);
shuffle(NoOfPacket);
receive(NoOfPacket);
free(readdata);
free(transdata);
getch();
}
Output:
Enter The message to be Transmitted :
hi, it was nice meeting u on sunday
The Message has been divided as follows
Packet No. Data
1 hi,
2 it

KMIT Page no:59


Department of CSE Computer Networks & Web Technologies Lab

3 wa
4sn
5 ice
6 me
7 eti
8 ng
9uo
10 n s
11 und
12 ay
Packets received in the following order
4 2 6 3 5 1 8 9 11 7 12 10
Packets in order after sorting..
1 2 3 4 5 6 7 8 9 10 11 12
Message received is :
hi, it was nice meeting u on Sunday

KMIT Page no:60


Department of CSE Computer Networks & Web Technologies Lab

10. Implement Packet Capture Using Wire shark


Install the Wireshark Network Analyzer

i.Set up the Packet Capture

1. Click View > Wireless Toolbar. The Wireless Toolbar will appear just below the Main
toolbar.

2. Use the Wireless Toolbar to configure the desired channel and channel width.

3. Under Capture, click on AirPcap USB wireless capture adapter to select the capture
interface.

Note: If the AirPcap isn't listed, press F5 to refresh the list of available packet capture
interfaces.

KMIT Page no:61


Department of CSE Computer Networks & Web Technologies Lab

Note: The AirPcap has been discontinued by RiverBed and is 802.11n only.

4. Click the Start Capture button to begin the capture.

5. When you are finished capturing, click the Stop button.

Saving the Capture

1. To save the capture, click File > Save.

KMIT Page no:62


Department of CSE Computer Networks & Web Technologies Lab

2. Name the file, and click Save.

Note: .Pcap and .Pcap-ng are good filetypes to use for the capture if you plan to use Eye P.A. to
open the capture.

3. Eye P.A. can now open the capture file.

KMIT Page no:63


Department of CSE Computer Networks & Web Technologies Lab

ii Starting Wire shark

Two different methods for starting Wireshark are available. These include the Start menu and the
Run command box.

Method 1 - Start Menu

To start Wireshark using the Start menu:

1. Open the Start menu.


2. Select All Programs.
3. Select Wireshark.

Method 2 - Run Command

To start Wireshark using the Run command box:

1. Open the Start menu or press the Windows key + R.


2. Type Wireshark in the Run command box.
3. Press Enter.

Activity 2 - Open the Capture Interfaces Dialog Box

Three different methods for opening the Capture Interfaces dialog box are available. These
include the Capture menu, the Capture Interfaces toolbar button, and the Capture Interfaces
keyboard shortcut.

Method 1 - Capture Menu

To open the Capture Interfaces dialog box using the Capture menu:

1. Select the Capture menu.


2. Select Interfaces.

Method 2 - Capture Interfaces Toolbar Button

To open the Capture Interfaces dialog box using the Capture interfaces Toolbar button:

1. Locate the toolbar button with the help text List the available capture interfaces. This
should be the first toolbar button on the left.

KMIT Page no:64


Department of CSE Computer Networks & Web Technologies Lab

2. Click the Capture Interfaces toolbar button.

Method 3 - Capture Interfaces Keyboard Shortcut

To open the Capture Interfaces dialog box using the Capture interfaces keyboard shortcut:

1. Press <Ctrl> + I.

Activity 3 - Start a Wireshark Capture

To start a Wireshark capture from the Capture Interfaces dialog box:

1. Observe the available interfaces. If you have multiple interfaces displayed, look for the
interface with the highest packet count. This is your most active network interface.
2. Select the interface you want to use for the capture using the check box on the left.
3. Select Start to begin the capture.
iii Packet Capture

Wireshark

Wireshark is a network protocol analyzer that can be installed on Windows, Linux and Mac. It
provides a comprehensive capture and is more informative than Fiddler.

To use:

1. Install Wireshark.
2. Open your Internet browser.
3. Clear your browser cache.
4. Open Wireshark
5. Click on "Capture > Interfaces". A pop up window will show up.
6. You probably want to capture traffic that goes through your ethernet driver. Click on
the Start button to start capturing traffic via this interface.
7. Visit the URL that you wanted to capture the traffic from.
8. Go back to your Wireshark screen and press Ctrl + E to stop capturing.
9. After the traffic capture is stopped, please save the captured traffic into a *.pcap format file and
attach it to your support ticket.

KMIT Page no:65


Department of CSE Computer Networks & Web Technologies Lab

 f you are using HTTPS, please disable it in your test environment so Wireshark can be used.
 Wireshark cannot sniff traffic within the same machine (localhost) on Windows. If you need to
sniff local traffic on Windows, try Fiddler.

iii.Viewing Packets You Have Captured

Once you have captured some packets or you have opened a previously saved capture file, you
can view the packets that are displayed in the packet list pane by simply clicking on a packet in
the packet list pane, which will bring up the selected packet in the tree view and byte view panes.

You can then expand any part of the tree to view detailed information about each protocol in each
packet. Clicking on an item in the tree will highlight the corresponding bytes in the byte view. An
example with a TCP packet selected is shown in Figure 6.1, “Wireshark with a TCP packet
selected for viewing”. It also has the Acknowledgment number in the TCP header selected, which
shows up in the byte view as the selected bytes.

Wireshark with a TCP packet selected for viewing

KMIT Page no:66


Department of CSE Computer Networks & Web Technologies Lab

You can also select and view packets the same way while Wireshark is capturing if you selected
“Update list of packets in real time” in the “Capture Preferences” dialog box.

In addition you can view individual packets in a separate window as shown in Figure 6.2,
“Viewing a packet in a separate window”. You can do this by double-clicking on an item in the
packet list or by selecting the packet in which you are interested in the packet list pane and
selecting View → Show Packet in New Window. This allows you to easily compare two or more
packets, even across multiple files.

Figure 6.2. Viewing a packet in a separate window

KMIT Page no:67


Department of CSE Computer Networks & Web Technologies Lab

11. How to Run NMAP SCAN

Are you worried about the security of your network or the security of someone else's?
Ensuring that your router is protected from unwanted intruders is one of the foundations of a
secure network. One of the basic tools for this job is Nmap, or Network Mapper. This
program will scan a target and report which ports are open and which are closed, among
other things. Security specialists use this program to test the security of a network. To learn
how to use it yourself, see Step 1 below.

Download the Nmap installer. This can be found for free from the developer’s website. It is
highly recommended that you download directly from the developer to avoid any potential
viruses or fake files. Downloading the Nmap installer includes Zenmap, the graphical interface
for Nmap which makes it easy for newcomers to perform scans without having to learn
command lines.

 The Zenmap program is available for Windows, Linux, and Mac OS X. You can find the
installation files for all operating systems on the Nmap website.

KMIT Page no:68


Department of CSE Computer Networks & Web Technologies Lab

Install Nmap. Run the installer once it is finished downloading. You will be asked which components
you would like to install. In order to get the full benefit of Nmap, keep all of these checked. Nmap will
not install any adware or spyware.

KMIT Page no:69


Department of CSE Computer Networks & Web Technologies Lab

3 Run the “Nmap – Zenmap” GUI program. If you left your settings at default during
installation, you should be able to see an icon for it on your desktop. If not, look in your Start
menu. Opening Zenmap will start the program.

4 Enter in the target for your scan. The Zenmap program makes scanning a fairly simple
process. The first step to running a scan is choosing your target. You can enter a domain
(example.com), an IP address (127.0.0.1), a network (192.168.1.0/24), or a combination of those.
 Depending on the intensity and target of your scan, running an Nmap scan may be against
the terms of your internet service provider, and may land you in hot water. Always check
your local laws and your ISP contract before performing Nmap scans on targets other than
your own network.

KMIT Page no:70


Department of CSE Computer Networks & Web Technologies Lab

5 Choose your Profile. Profiles are preset groupings of modifiers that change what is scanned.
The profiles allow you to quickly select different types of scans without having to type in the
modifiers on the command line. Choose the profile that best fits your needs:[1]

 Intense scan - A comprehensive scan. Contains Operating System (OS) detection, version
detection, script scanning, traceroute, and has aggressive scan timing. This is considered an
intrusive scan.
 Ping scan - This scan simply detects if the targets are online, it does not scan any ports.
 Quick scan - This is quicker than a regular scan due to aggressive timing and only
scanning select ports.
 Regular scan - This is the standard Nmap scan without any modifiers. It will return ping
and return open ports on the target.

KMIT Page no:71


Department of CSE Computer Networks & Web Technologies Lab

6
Click Scan to start scanning. The active results of the scan will be displayed in the Nmap Output tab.
The time the scan takes will depend on the scan profile you chose, the physical distance to the target, and
the target’s network configuration.

KMIT Page no:72


Department of CSE Computer Networks & Web Technologies Lab

7 Read your results. Once the scan is finished, you’ll see the message “Nmap done” at the
bottom of the Nmap Output tab. You can now check your results, depending on the type of scan
you performed. All of the results will be listed in the main Nmap Output tab, but you can use the
other tabs to get a better look at specific data.[2]

 Ports/Hosts - This tab will show the results of your port scan, including the services for
those ports.

KMIT Page no:73


Department of CSE Computer Networks & Web Technologies Lab

Topology - This shows the traceroute for the scan you performed. You can see how many hops
your data goes through to reach the target.

KMIT Page no:74


Department of CSE Computer Networks & Web Technologies Lab

Host Details - This shows a summary of your target learned through scans, such as the number
of ports, IP addresses, hostnames, operating systems, and more.

Scans - This tab stores the commands of your previously-run scans. This allows you to quickly
re-scan with a specific set of parameters.

KMIT Page no:75


Department of CSE Computer Networks & Web Technologies Lab

Method 2:
Using the Command Line
Install Nmap. Before using Nmap, you will need to install it so that you can run it from the
command line of your operating system. Nmap is small and available for free from the
developer. Follow the instructions below for your operating system:

 Linux - Download and install Nmap from your repository. Nmap is available through most
of the major Linux repositories. Enter in the command below based on your distribution:

KMIT Page no:76


Department of CSE Computer Networks & Web Technologies Lab

 Red Hat, Fedora, SUSE


rpm -vhU http://nmap.org/dist/nmap-6.40-1.i386.rpm (32-bit) OR
rpm -vhU http://nmap.org/dist/nmap-6.40-1.x86_64.rpm (64-bit)
 Debian, Ubuntu
sudo apt-get install nmap
 Windows - Download the Nmap installer. This can be found for free from the developer’s
website. It is highly recommended that you download directly from the developer to avoid
any potential viruses or fake files. Using the installer allows you to quickly install the
command line Nmap tools without having to worry about extracting to the right folder.

KMIT Page no:77


Department of CSE Computer Networks & Web Technologies Lab

 If you don’t want the Zenmap graphical user interface, you can uncheck it during the
installation process.
 Mac OS X – Download the Nmap disk image. This can be found for free from the
developer’s website. It is highly recommended that you download directly from the
developer to avoid any potential viruses or fake files. Use the included installer to install
Nmap on your system. Nmap requires OS X 10.6 or later.

KMIT Page no:78


Department of CSE Computer Networks & Web Technologies Lab

2 Open your command line. Nmap commands are run from the command line, and the results
are displayed beneath the command. You can use variables to modify the scan. You can run the
scan from any directory on the command line.
 Linux - Open the terminal if you are using a GUI for your Linux distribution. The

location of the terminal varies by distribution

KMIT Page no:79


Department of CSE Computer Networks & Web Technologies Lab

Windows - This can be accessed by pressing the Windows key + R and then typing “cmd”
into the Run field. Windows 8 users can press Windows key + X and select Command
Prompt from the menu. You can run an Nmap scan from any directory.

KMIT Page no:80


Department of CSE Computer Networks & Web Technologies Lab

Mac OS X - Open the Terminal application located in the Utility subfolder of your Applications folder.

KMIT Page no:81


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:82


Department of CSE Computer Networks & Web Technologies Lab

3 Run a scan of you target’s ports. To start a basic scan, type nmap<target>. This will ping the
target and scan the ports. This is an easily-detected scan. The results will be displayed on your
screen. You may need to scroll back up to see all of the results.
 Depending on the intensity and target of your scan, running an Nmap scan may be against

the terms of your internet service provider, and may land you in hot water. Always check
your local laws and your ISP contract before performing Nmap scans on targets other than
your own network.

KMIT Page no:83


Department of CSE Computer Networks & Web Technologies Lab

4 Run a modified scan. You can use command line variables to change the parameters of the
scan, resulting in more detailed or less detailed results. Changing the scan variables will change
the intrusiveness of the scan. You can add multiple variables by placing a space between each
one. Variables come before the target: nmap<variable><variable><target>[3]

 -sS - This is a SYN stealth scan. It is less detectable than a standard scan, but may take
longer. Many modern firewalls can detect an –sS scan.
 -sn - This is a ping scan. This will disable port scanning, and will only check to see if the
host is online.
 -O - This is an operating system scan. The scan will attempt to determine the operating
system of the target.
 -A - This variable enables several of the most commonly used scans: OS detection, version
detection, script scanning, and traceroute.

KMIT Page no:84


Department of CSE Computer Networks & Web Technologies Lab

 -F - This enables fast mode, and will reduce the number of ports scanned.
 -v - This will show more information in your results, making them easier to read.

5. Output the scan to an XML file. You can set your scan results to be outputted as an XML file so that
you can easily read them in any web browser. To do this, you will need to use the -oX variable, as well as
set a filename for the new XML file. A completed command would look similar to nmap –oX Scan
Results.xml <target>.
 The XML file will be saved to whatever your current working location is.

KMIT Page no:85


Department of CSE Computer Networks & Web Technologies Lab

12. Operating System Detection using Nmap

OS Detection:
One of Nmap's best-known features is remote OS detection using TCP/IP stack fingerprinting.
Nmap sends a series of TCP and UDP packets to the remote host and examines practically
every bit in the responses.
After performing dozens of tests such as TCP ISN sampling, TCP options support and
ordering, IP ID sampling, and the initial window size check, Nmap compares the results to its
nmap-os-db database of more than 2,600 known OS fingerprints and prints out the OS details
if there is a match.
Each fingerprint includes a freeform textual description of the OS, and a classification which
provides the vendor name (e.g. Sun), underlying OS (e.g. Solaris), OS generation (e.g. 10), and
device type (general purpose, router, switch, game console, etc).
Most fingerprints also have a Common Platform Enumeration (CPE) representation, like
cpe:/o:linux:linux_kernel:2.6.
If Nmap is unable to guess the OS of a machine, and conditions are good (e.g. at least one
open port and one closed port were found), Nmap will provide a URL you can use to submit
the fingerprint if you know (for sure) the OS running on the machine. By doing this you
contribute to the pool of operating systems known to Nmap and thus it will be more accurate
for everyone.
OS detection enables some other tests which make use of information that is gathered during
the process anyway. One of these is TCP Sequence Predictability Classification.
This measures approximately how hard it is to establish a forged TCP connection against the
remote host.
It is useful for exploiting source-IP based trust relationships (rlogin, firewall filters, etc) or for
hiding the source of an attack.
This sort of spoofing is rarely performed any more, but many machines are still vulnerable to
it.
The actual difficulty number is based on statistical sampling and may fluctuate.
It is generally better to use the English classification such as “worthy challenge” or “trivial
joke”.
This is only reported in normal output in verbose (-v) mode.
When verbose mode is enabled along with -O, IP ID sequence generation is also reported.
Most machines are in the “incremental” class, which means that they increment the ID field in
the IP header for each packet they send.
This makes them vulnerable to several advanced information gathering and spoofing attacks.

KMIT Page no:86


Department of CSE Computer Networks & Web Technologies Lab

Another bit of extra information enabled by OS detection is a guess at a target's uptime.


This uses the TCP timestamp option (RFC 1323) to guess when a machine was last rebooted.
The guess can be inaccurate due to the timestamp counter not being initialized to zero or the
counter overflowing and wrapping around, so it is printed only in verbose mode.
OS detection is enabled and controlled with the following options:
-O (Enable OS detection)
Enables OS detection, as discussed above. Alternatively, you can use -A to enable OS
detection along with other things.
--osscan-limit (Limit OS detection to promising targets)
OS detection is far more effective if at least one open and one closed TCP port are found. Set
this option and Nmap will not even try OS detection against hosts that do not meet this criteria.
This can save substantial time, particularly on -Pn scans against many hosts. It only matters
when OS detection is requested with -O or -A.
--osscan-guess; --fuzzy (Guess OS detection results)
When Nmap is unable to detect a perfect OS match, it sometimes offers up near-matches as
possibilities.
The match has to be very close for Nmap to do this by default. Either of these (equivalent)
options make Nmap guess more aggressively.
Nmap will still tell you when an imperfect match is printed and display its confidence level
(percentage) for each guess.
--max-os-tries (Set the maximum number of OS detection tries against a target)
When Nmap performs OS detection against a target and fails to find a perfect match, it usually
repeats the attempt.
By default, Nmap tries five times if conditions are favorable for OS fingerprint submission,
and twice when conditions aren't so good.
Specifying a lower --max-os-tries value (such as 1) speeds Nmap up, though you miss out on
retries which could potentially identify the OS.
Alternatively, a high value may be set to allow even more retries when conditions are
favorable.
This is rarely done, except to generate better fingerprints for submission and integration into
the Nmap OS database.

KMIT Page no:87


Department of CSE Computer Networks & Web Technologies Lab

13. Do the following using NS2 Simulator


i. NS2 Simulator-Introduction
ii. Simulate to Find the Number of Packets Dropped
iii. Simulate to Find the Number of Packets Dropped by TCP/UDP
iv. Simulate to Find the Number of Packets Dropped due to Congestion
v. Simulate to Compare Data Rate& Throughput.
vi. Simulate to Plot Congestion for Different Source/Destination
vii. Simulate to Determine the Performance with respect to Transmission of
Packets

i. Introduction to NS-2:

NS2 is an open-source simulation tool that runs on Linux. It is a discreet event simulator targeted
at networking research and provides substantial support for simulation of routing, multicast
protocols and IP protocols, such as UDP, TCP, RTP and SRM over wired and wireless (local and
satellite) networks.
Widely known as NS2, is simply an event driven simulation tool.

Useful in studying the dynamic nature of communication networks.

Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2.

In general, NS2 provides users with a way of specifying such network protocols and simulating
their corresponding behaviors.

Basic Architecture of NS2

KMIT Page no:88


Department of CSE Computer Networks & Web Technologies Lab

TCL – Tool Command Language

Tcl is a very simple programming language. If you have programmed before, you can learn
enough to write interesting Tcl programs within a few hours. This page provides a quick
overview of the main features of Tcl. After reading this you'll probably be able to start writing
simple Tcl scripts on your own; however, we recommend that you consult one of the many
available Tcl books for more complete information.

Basic syntax

Tcl scripts are made up of commands separated by newlines or semicolons. Commands all have
the same basic form illustrated by the following example:
expr 20 + 10

This command computes the sum of 20 and 10 and returns the result, 30. You can try out this
example and all the others in this page by typing them to a Tcl application such as tclsh; after a
command completes, tclsh prints its result.
Each Tcl command consists of one or more words separated by spaces.
In this example there are four words: expr, 20, +, and 10. The first word is the name of a
command and the other words are arguments to that command. All Tcl commands consist of
words,
but different commands treat their arguments differently. The expr command treats all of its
arguments together as an arithmetic expression, computes the result of that expression, and
returns the result as a string. In the expr command the division into words isn't significant: you
could just as easily have invoked the same command as
expr 20+10
However, for most commands the word structure is important, with each word used for a distinct
purpose.
All Tcl commands return results. If a command has no meaningful result then it returns an empty
string as its result.
Variables
Tcl allows you to store values in variables and use the values later in commands. The set
command is used to write and read variables. For example, the following command modifies the
variable x to hold the value 32:
set x 32

The command returns the new value of the variable. You can read the value of a variable by
invoking set with only a single argument:
set x
You don't need to declare variables in Tcl: a variable is created automatically the first time it is
set. Tcl variables don't have types: any variable can hold any value.
To use the value of a variable in a command, use variable substitution as in the following
example:

KMIT Page no:89


Department of CSE Computer Networks & Web Technologies Lab

expr $x*3
When a $ appears in a command, Tcl treats the letters and digits following it as a variable name,
and substitutes the value of the variable in place of the name. In this example, the actual
argument received by the expr command will be 32*3 (assuming that variable x was set as in the
previous example). You can use variable substitution in any word of any command, or even
multiple times within a word:
set cmd expr
set x 11
$cmd $x*$x

Command substitution
You can also use the result of one command in an argument to another command. This is called
command substitution:
set a 44
set b [expr $a*4]

When a [ appears in a command, Tcl treats everything between it and the matching ] as a nested
Tcl command. Tcl evaluates the nested command and substitutes its result into the enclosing
command in place of the bracketed text. In the example above the second argument of the second
set command will be 176.

Quotes and braces

Double-quotes allow you to specify words that contain spaces. For example, consider the
following script:
set x 24
set y 18
set z "$x + $y is [expr $x + $y]"
After these three commands are evaluated variable z will have the value 24 + 18 is 42.
Everything between the quotes is passed to the set command as a single word. Note that (a)
command and variable substitutions are performed on the text between the quotes, and (b) the
quotes themselves are not passed to the command. If the quotes were not present, the set
command would have received 6 arguments, which would have caused an error.
Curly braces provide another way of grouping information into words. They are different from
quotes in that no substitutions are performed on the text between the curly braces:
set z {$x + $y is [expr $x + $y]}
This command sets variable z to the value "$x + $y is [expr $x + $y]".

Control structures
Tcl provides a complete set of control structures including commands for conditional execution,
looping, and procedures. Tcl control structures are just commands that take Tcl scripts as
arguments.

The example below creates a Tcl procedure called power, which raises a base to an integer
power:

KMIT Page no:90


Department of CSE Computer Networks & Web Technologies Lab

proc power {base p} {


set result 1
while {$p > 0} {
set result [expr $result * $base]
set p [expr $p - 1]
}
return $result
}

This script consists of a single command, proc. The proc command takes three arguments: the
name of a procedure, a list of argument names, and the body of the procedure, which is a Tcl
script. Note that everything between the curly brace at the end of the first line and the curly brace
on the last line is passed verbatim to proc as a single argument. The proc command creates a new
Tcl command named power that takes two arguments. You can then invoke power with
commands like the following:
power 2 6
power 1.15 5
When power is invoked, the procedure body is evaluated. While the body is executing it can
access its arguments as variables: base will hold the first argument and p will hold the second.
The body of the power procedure contains three Tcl commands: set, while, and return. The while
command does most of the work of the procedure. It takes two arguments, an expression ($p > 0)
and a body, which is another Tcl script. The while command evaluates its expression argument
using rules similar to those of the C programming language and if the result is true (nonzero)
then it evaluates the body as a Tcl script. It repeats this process over and over until eventually the
expression evaluates to false (zero). In this case the body of the while command multiplied the
result value by base and then decrements p. When p reaches zero the result contains the desired
power of base. The return command causes the procedure to exit with the value of variable result
as the procedure's result.

Where do commands come from?

As you have seen, all of the interesting features in Tcl are represented by commands. Statements are
commands, expressions are evaluated by executing commands, control structures are commands, and
procedures are commands.
Tcl commands are created in three ways. One group of commands is provided by the Tcl interpreter
itself. These commands are called builtin commands.
They include all of the commands you have seen so far and many more (see below). The builtin
commands are present in all Tcl applications.
The second group of commands is created using the Tcl extension mechanism.
Tcl provides APIs that allow you to create a new command by writing a command procedure in C or
C++ that implements the command.
You then register the command procedure with the Tcl interpreter by telling Tcl the name of the
command that the procedure implements.
In the future, whenever that particular name is used for a Tcl command, Tcl will call your command
procedure to execute the command.
The builtin commands are also implemented using this same extension mechanism; their command
procedures are simply part of the Tcl library.

KMIT Page no:91


Department of CSE Computer Networks & Web Technologies Lab

When Tcl is used inside an application, the application incorporates its key features into Tcl using the
extension mechanism.
Thus the set of available Tcl commands varies from application to application. There are also
numerous extension packages that can be incorporated into any Tcl application.

One of the best known extensions is Tk, which provides powerful facilities for building graphical
user interfaces.
Other extensions provide object-oriented programming, database access, more graphical capabilities,
and a variety of other features.
One of Tcl's greatest advantages for building integration applications is the ease with which it can be
extended to incorporate new features or communicate with other resources.
The third group of commands consists of procedures created with the proc command, such as the
power command created above.
Typically, extensions are used for lower-level functions where C programming is convenient, and
procedures are used for higher-level functions where it is easier to write in Tcl.

Wired TCL Script Components


Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation

NS Simulator Preliminaries.
Initialization and termination aspects of the ns simulator.
Definition of network nodes, links, queues and topology.
Definition of agents and of applications.
The nam visualization tool.
Tracing and random variables.

Features of NS2

NS2 can be employed in most unix systems and windows. Most of the NS2 code is in C++. It uses
TCL as its scripting language, Otcl adds object orientation to TCL.NS(version 2) is an object
oriented, discrete event driven network simulator that is freely distributed and open source.
Traffic Models: CBR, VBR, Web etc

Protocols: TCP, UDP, HTTP, Routing algorithms,MAC etc

Error Models: Uniform, bursty etc

Misc: Radio propagation, Mobility models , Energy Models

Topology Generation tools

KMIT Page no:92


Department of CSE Computer Networks & Web Technologies Lab

Visualization tools (NAM), Tracing

Structure of NS
● NS is an object oriented discrete event simulator
– Simulator maintains list of events and executes one event after another
– Single thread of control: no locking or race conditions
● Back end is C++ event scheduler
– Protocols mostly
– Fast to run, more control
Front end is OTCL

Creating scenarios, extensions to C++ protocols


fast to write and change

Platforms
It can be employed in most unixsystems(FreeBSD, Linux, Solaris) and Windows.
Source code
Most of NS2 code is in C++
Scripting language
It uses TCL as its scripting language OTcl adds object orientation to TCL.
Protocols implemented in NS2
Transport layer(Traffic Agent) – TCP, UDP
Network layer(Routing agent)

Interface queue – FIFO queue, Drop Tail queue, Priority queue


Logic link contol layer – IEEE 802.2, AR
How to use NS2
Design Simulation – Determine simulation scenario
Build ns-2 script using tcl.
Run simulation
Simulation with NS2
Define objects of simulation.
Connect the objects to each other
Start the source applications. Packets are then created and are transmitted through network.
Exit the simulator after a certain fixed time.
NS programming Structure
● Create the event scheduler
● Turn on tracing
● Create network topology
● Create transport connections
● Generate traffic
● Insert errors

KMIT Page no:93


Department of CSE Computer Networks & Web Technologies Lab

Initialization and Termination of TCL Script in NS-2


An ns simulation starts with the command
set ns [new Simulator]
Which is thus the first line in the tcl script? This line declares a new variable as using the
setcommand, you can call this variable as you wish, In general people declares it as ns because it is
an instance of the Simulator class, so an object the code[new Simulator] is indeed the installation
of the class Simulator using the reserved word new.
In order to have output files with data on the simulation (trace files) or files used for visualization
(nam files), we need to create the files using “open” command:
#Open the Trace file
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
The above creates a dta trace file called “out.tr” and a nam visualization trace file called
“out.nam”. Within the tcl script, these files are not called explicitly by their names, but instead by
pointers that are declared above and called “tracefile1” and “namfile” respectively. Remark that
they begin with a # symbol. The second line open the file ―out.tr‖ to be used for writing, declared
with the letter “w”. The third line uses a simulator method called trace-all that have as parameter
the name of the file where the traces will go.
The last line tells the simulator to record all simulation traces in NAM input format. It also
gives the file name that the trace will be written to later by the command $ns flush-trace.in our
case, this will be the file pointed at by the pointer “$namfile” i.e. the file “out.tr”.
The termination of the program is done using a “finish” procedure.
#Define a “finish” procedure
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec namout.nam&
Exit 0
}
The word proc declares a procedure in this case called finish and without arguments. The word
global is used to tell that we are using variables declared outside the procedure. The simulator
method ―flush-trace” will dump the traces on the respective files. The tcl command ―close”
closes the trace files defined before and exec executes the nam program for visualization. The

KMIT Page no:94


Department of CSE Computer Networks & Web Technologies Lab

command exit will ends the application and return the number 0 as status to the system. Zero is the
default for a clean exit. Other values can be used to say that is a exit because something fails.
At the end of ns program we should call the procedure ―finish‖ and specify at what time the
termination should occur. For example,
$ns at 125.0 “finish”
will be used to call ―finish‖ at time 125sec.Indeed,theat method of the simulator allows us to
schedule events explicitly.
The simulation can then begin using the command
$ns run
Definition of a network of links and nodes
The way to define a node is
set n0 [$ns node]
The node is created which is printed by the variable n0. When we shall refer to that node in the script
we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An example of a definition
of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace ―duplex-link‖ by
―simplex-link‖.
In NS, an output queue of a node is implemented as a part of each link whose input is that node. The
definition of the link then includes the way to handle overflow at that queue. In our case, if the buffer
capacity of the output queue is exceeded then the last packet to arrive is dropped. Many alternative
options exist, such as the RED (Random Early Discard) mechanism, the FQ (Fair Queuing), the DRR
(Deficit Round Robin), the stochastic Fair Queuing (SFQ) and the CBQ (which including a priority
and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is that node. We
should also define the buffer capacity of the queue related to each link. An example would be:
#set Queue Size of link (n0-n2) to 20
$ns queue-limit $n0 $n2 20
Agents and Applications
We need to define routing (sources, destinations) the agents (protocols) the application that use them.
FTP over TCP
TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements created by the
destination to know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas. The type of
agent appears in the first line:
set tcp [new Agent/TCP]
The command $ns attach-agent $n0 $tcpdefines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink]
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp

KMIT Page no:95


Department of CSE Computer Networks & Web Technologies Lab

set null [new Agent/Null]


$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_2
#setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packetsize_ 100
$cbr set rate_ 0.01Mb
$cbr set random_ false
Above shows the definition of a CBR application using a UDP agent
The command $ns attach-agent $n4 $sink defines the destination node. The command $ns connect
$tcp $sink finally makes the TCP connection between the source and destination nodes.
TCP has many parameters with initial fixed defaults values that can be changed if mentioned
explicitly. For example, the default TCP packet size has a size of 1000bytes.This can be changed to
another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify them with
different colors in the visualization part. This is done by the command $tcp set fid_ 1 that assigns to
the TCP connection a flow identification of ―1‖.We shall later give the flow identification of ―2‖ to
the UDP connection.
CBR over UDP
A UDP source and destination is defined in a similar way as in the case of TCP.
Instead of defining the rate in the command $cbr set rate_ 0.01Mb, one can define the time interval
between transmission of packets using the command.
$cbr set interval_ 0.005
The packet size can be set to some value using
$cbr set packetSize_ <packet size>
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur. The
initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format:
$ns at <time><event>
The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following command
$ns at 0.1 “$cbr start”
$ns at 1.0 “ $ftp start”
$ns at 124.0 “$ftp stop”
$ns at 124.5 “$cbr stop”
Structure of Trace Files
When tracing into an output ASCII file, the trace is organized in 12 fields as follows in fig shown
below, The meaning of the fields are:

KMIT Page no:96


Department of CSE Computer Networks & Web Technologies Lab

1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one can
further use this field for analysis purposes; it is also used when specifying stream color for the NAM
display.
9. This is the source address given in the form of ―node.port‖.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP implementations
in a real network do not use sequence number, ns keeps track of UDP packet sequence number for
analysis purposes
12. The last field shows the Unique id of the packet.

XGRAPH
The xgraph program draws a graph on an x-display given data read from either data file or from
standard input if no files are specified. It can display upto 64 independent data sets using different
colors and line styles for each set. It annotates the graph with a title, axis labels, grid lines or tick
marks, grid labels and a legend.
Syntax:
Options are listed here
/-bd <color> (Border)
This specifies the border color of the xgraph window.
/-bg<color> (Background)
This specifies the background color of the xgraph window.
/-fg<color> (Foreground)
This specifies the foreground color of the xgraph window.
/-lf<fontname> (LabelFont)
All axis labels and grid labels are drawn using this font.
/-t<string> (Title Text)
This string is centered at the top of the graph.
/-x <unit name> (XunitText)

KMIT Page no:97


Department of CSE Computer Networks & Web Technologies Lab

This is the unit name for the x-axis. Its default is ―X‖.
/-y <unit name> (YunitText)
This is the unit name for the y-axis. Its default is ―Y‖.

Awk- An Advanced
awk is a programmable, pattern-matching, and processing tool available in UNIX. It
works equally well with text and numbers.
awk is not just a command, but a programming language too. In other words, awk utility is a pattern
scanning and processing language. It searches one or more files to see if they contain lines that match
specified patterns and then perform associated actions, such as writing the line to the standard output
or incrementing a counter each time it finds a match.
Syntax:
awk option ‘selection_criteria {action}’ file(s)
Here, selection_criteria filters input and select lines for the action component to act upon. The
selection_criteria is enclosed within single quotes and the action within the curly braces. Both the
selection_criteria and action forms an awk program.
Example: $ awk „/manager/ {print}‟ emp.lst
Variables
Awk allows the user to use variables of there choice. You can now print a serial number, using the
variable kount, and apply it those directors drawing a salary exceeding 6700:
$ awk –F”|” „$3 == “director” && $6 > 6700 {
kount =kount+1
printf“ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }‟ empn.lst
THE –f OPTION: STORING awk PROGRAMS IN A FILE
You should holds large awk programs in separate file and provide them with the awk extension for
easier identification. Let’s first store the previous program in the file empawk.awk:
$ cat empawk.awk
Observe that this time we haven’t used quotes to enclose the awk program. You can now use awk
with the –f filename option to obtain the same output:

Awk –F”|” –f empawk.awkempn.lst

THE BEGIN AND END SECTIONS


Awk statements are usually applied to all lines selected by the address, and if there are no addresses,
then they are applied to every line of input. But, if you have to print something before processing the
first line, for example, a heading, then the BEGIN section can be used gainfully. Similarly, the end
section useful in printing some totals after processing is over.
The BEGIN and END sections are optional and take the form
BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You can use them
to print a suitable heading at the beginning and the average salary at the end.
BUILT-IN VARIABLES
Awk has several built-in variables. They are all assigned automatically, though it is also possible for
a user to reassign some of them. You have already used NR, which signifies the record number of the
current line. We’ll now have a brief look at some of the other variable.
The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field
delimiter. FS redefines this field separator, which in the sample database happens to be the |. When

KMIT Page no:98


Department of CSE Computer Networks & Web Technologies Lab

used at all, it must occur in the BEGIN section so that the body of the program knows its value
before it starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments, each
argument was separated from the other by a space. This is awk’s default output field separator, and
can reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting the print
arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don’t contain the
right number of fields. By using it on a file, say emp.lst, you can locate those lines not having 6
fields, and which have crept in due to faulty data entry:
$awk „BEGIN {FS = “|”}
NF! =6 { Print “Record No “, NR, “has”, “fields”}‟ empx.lst

ii Simulate to Find the Number of Packets Dropped


Simulate a three node point to point network with duplex links between them. Set queue size and
vary the bandwidth and find number of packets dropped.

KMIT Page no:99


Department of CSE Computer Networks & Web Technologies Lab

OUTPUT:

KMIT Page no:100


Department of CSE Computer Networks & Web Technologies Lab

iii. Simulate to Find the Number of Packets Dropped by TCP/UDP


Create a new Simulation Instance
set ns [new Simulator]
set bandwidth 1.75Mb
#Turn on the Trace and the animation files
set f [open out.tr w]
set nf [open out.nam w]
$ns trace-all $f
$ns namtrace-all $nf
#Define the finish procedure to perform at the end of the simulation
proc finish {} {
global f nf ns
$ns flush-trace
close $f
close $nf
exec namout.nam&
#exec awk -f 1.awk out.tr &
exit 0
}

#Create the nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
#Label the nodes
$n0 label "TCP Source"
$n1 label "UDP Source"
$n2 label "Sink"

#Set the color


$ns color 1 red

KMIT Page no:101


Department of CSE Computer Networks & Web Technologies Lab

$ns color 2 yellow


#Create the Topology
$ns duplex-link $n0 $n1 $bandwidth 10ms DropTail
$ns duplex-link $n1 $n2 1.75Mb 20ms DropTail

#Attach a Queue of size N Packets between the nodes n1 n2


$ns queue-limit $n1 $n2 10

#Make the Link Orientation


$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right

#Create a UDP Agent and attach to the node n1


set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0

#Create a CBR Traffic source and attach to the UDP Agent


set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0

#Specify the Packet Size and interval


$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005

#Create a Null Agent and attach to the node n2


set null0 [new Agent/Null]
$ns attach-agent $n2 $null0

#Connect the CBR Traffic source to the Null agent


$ns connect $udp0 $null0

KMIT Page no:102


Department of CSE Computer Networks & Web Technologies Lab

#Create a TCP agent and attach to the node n0


set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0

#Create a FTP source and attach to the TCP agent


set ftp0 [new Application/FTP]

#Attach the FTP source to the TCP Agent


$ftp0 attach-agent $tcp0

#Create a TCPSink agent and attach to the node n2


set sink [new Agent/TCPSink]
$ns attach-agent $n2 $sink

#Specify the Max file Size in Bytes


$ftp0 set maxPkts_ 1000

#Connect the TCP Agent with the TCPSink


$ns connect $tcp0 $sink

$udp0 set class_ 1


$tcp0 set class_ 2

#Schedule the Events


$ns at 0.1 "$cbr0 start"
$ns at 1.0 "$ftp0 start"
$ns at 4.0 "$ftp0 stop"
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run

KMIT Page no:103


Department of CSE Computer Networks & Web Technologies Lab

Now run the code using

ns filename.tcl

you will get something like this :

Also , a trace file has been generated which is out.tr . This trace file contains data related to
packets sent and packets recieved and about packet dropped .

Part of trace file is shown below :

KMIT Page no:104


Department of CSE Computer Networks & Web Technologies Lab

1. Event
This field defines the type of event :
+ :a packet enque event
- :a packet deque event
r :a packet reception event
d :a packet drop (e.g., sent to dropHead_) event
c :a packet collision at the MAC level

2. Time
This field defines the time at which packet tracing string is created .

3. From
This defines the source node of packet .

4. To
This defines the destination node of packet .

5. Packet Type
This field defines the transport layer protocol agent used (cbr,ftp) .

6. Packet Size
This field defines the size of packet in bytes .

KMIT Page no:105


Department of CSE Computer Networks & Web Technologies Lab

7. Flags
This field consist of 7 digit string whose values defines the following info :
“-”: disable
1st = “E”: ECN (Explicit Congestion Notification) echo is enabled.
2nd = “P”: the priority in the IP header is enabled.
3rd : Not in use
4th = “A”: Congestion action
5th = “E”: Congestion has occurred.
6th = “F”: The TCP fast start is used.
7th = “N”: Explicit Congestion Notification (ECN) is on.

8. FID
(Flow Id)

9. Source Address
This field defines the source address of the packet(actual origin of the packet) . This is defined in the
form of a.b (a defines the address and b defines the port number) .

10. Destination Address


This field defines the destination address of the packet(final destination of the packet) . This is also
define d in the form of a.b (a defines the address and b.defines the port address).

11. Seq number


This field defines the sequence number of the packet .

12. Packet ID
This field defines the packet id (usually same as sequence number).

Now we get the basic format of the trace file generated . Now we required to find the number of
dropped packets to find the throughput .

This can be done by using any programming language because we are only required to read the
trace file and need to count the number of packets (either sent, or received , or dropped)

1. Event
This field defines the type of event :
+ :a packet enque event
- :a packet deque event
r :a packet reception event
d :a packet drop (e.g., sent to dropHead_) event
c :a packet collision at the MAC level

2. Time
This field defines the time at which packet tracing string is created .

KMIT Page no:106


Department of CSE Computer Networks & Web Technologies Lab

3. From
This defines the source node of packet .

4. To
This defines the destination node of packet .

5. Packet Type
This field defines the transport layer protocol agent used (cbr,ftp) .

6. Packet Size
This field defines the size of packet in bytes .

7. Flags
This field consist of 7 digit string whose values defines the following info :
“-”: disable
1st = “E”: ECN (Explicit Congestion Notification) echo is enabled.
2nd = “P”: the priority in the IP header is enabled.
3rd : Not in use
4th = “A”: Congestion action
5th = “E”: Congestion has occurred.
6th = “F”: The TCP fast start is used.
7th = “N”: Explicit Congestion Notification (ECN) is on.

8. FID
(Flow Id)

9. Source Address
This field defines the source address of the packet(actual origin of the packet) . This is defined in the
form of a.b (a defines the address and b defines the port number) .

10. Destination Address


This field defines the destination address of the packet(final destination of the packet) . This is also
define d in the form of a.b (a defines the address and b.defines the port address).

11. Seq number


This field defines the sequence number of the packet .

12. Packet ID
This field defines the packet id (usually same as sequence number).

Now we get the basic format of the trace file generated . Now we required to find the number of
dropped packets to find the throughput .

This can be done by using any programming language because we are only required to read the
trace file and need to count the number of packets (either sent, or received , or dropped)

KMIT Page no:107


Department of CSE Computer Networks & Web Technologies Lab

Now to plot the graph (dropped packets vs bandwidth) , you need to install the xgraph (a tool
that takes the coordinates as input and plot the corrosponding graph)

To insallxgraph

sudo apt-get install ns2 namxgraph

Now create a file graph.xg

KMIT Page no:108


Department of CSE Computer Networks & Web Technologies Lab

iv. Simulate to Find the Number of Packets Dropped due to Congestion


t ns [ new Simulator ]
set nf [ open lab4.nam w ]
$ns namtrace-all $nf
set tf [ open lab4.tr w ]
$ns trace-all $tf
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$ns duplex-link $n0 $n4 1005Mb 1ms DropTail
$ns duplex-link $n1 $n4 50Mb 1ms DropTail
$ns duplex-link $n2 $n4 2000Mb 1ms DropTail
$ns duplex-link $n3 $n4 200Mb 1ms DropTail
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
set p1 [new Agent/Ping] # letters A and P should be capital

KMIT Page no:109


Department of CSE Computer Networks & Web Technologies Lab

$ns attach-agent $n0 $p1


$p1 set packetSize_ 50000
$p1 set interval_ 0.0001
set p2 [new Agent/Ping] # letters A and P should be capital
$ns attach-agent $n1 $p2
set p3 [new Agent/Ping] # letters A and P should be capital
$ns attach-agent $n2 $p3
$p3 set packetSize_ 30000
$p3 set interval_ 0.00001
set p4 [new Agent/Ping] # letters A and P should be capital
$ns attach-agent $n3 $p4
set p5 [new Agent/Ping] # letters A and P should be capital
$ns attach-agent $n5 $p5
$ns queue-limit $n0 $n4 5
$ns queue-limit $n2 $n4 3
$ns queue-limit $n4 $n5 2
Agent/Ping instprocrecv {from rtt} {
$self instvar node_
puts "node [$node_ id]received answer from $from with round trip time $rtt msec"
}
# please provide space between $node_ and id. No space between $ and from. No space
between and $ and rtt */
$ns connect $p1 $p5
$ns connect $p3 $p4
proc finish { } {
global ns nftf
$ns flush-trace
close $nf
close $tf
exec nam lab4.nam &
exit 0

KMIT Page no:110


Department of CSE Computer Networks & Web Technologies Lab

}
$ns at 0.1 "$p1 send"
$ns at 0.2 "$p1 send"
$ns at 0.3 "$p1 send"
$ns at 0.4 "$p1 send"
$ns at 0.5 "$p1 send"
$ns at 0.6 "$p1 send"
$ns at 0.7 "$p1 send"
$ns at 0.8 "$p1 send"
$ns at 0.9 "$p1 send"
$ns at 1.0 "$p1 send"
$ns at 1.1 "$p1 send"
$ns at 1.2 "$p1 send"
$ns at 1.3 "$p1 send"
$ns at 1.4 "$p1 send"
$ns at 1.5 "$p1 send"
$ns at 1.6 "$p1 send"
$ns at 1.7 "$p1 send"
$ns at 1.8 "$p1 send"
$ns at 1.9 "$p1 send"
$ns at 2.0 "$p1 send"
$ns at 2.1 "$p1 send"
$ns at 2.2 "$p1 send"
$ns at 2.3 "$p1 send"
$ns at 2.4 "$p1 send"
$ns at 2.5 "$p1 send"
$ns at 2.6 "$p1 send"
$ns at 2.7 "$p1 send"
$ns at 2.8 "$p1 send"
$ns at 2.9 "$p1 send"
$ns at 0.1 "$p3 send"

KMIT Page no:111


Department of CSE Computer Networks & Web Technologies Lab

$ns at 0.2 "$p3 send"


$ns at 0.3 "$p3 send"
$ns at 0.4 "$p3 send"
$ns at 0.5 "$p3 send"
$ns at 0.6 "$p3 send"
$ns at 0.7 "$p3 send"
$ns at 0.8 "$p3 send"
$ns at 0.9 "$p3 send"
$ns at 1.0 "$p3 send"
$ns at 1.1 "$p3 send"
$ns at 1.2 "$p3 send"
$ns at 1.3 "$p3 send"
$ns at 1.4 "$p3 send"
$ns at 1.5 "$p3 send"
$ns at 1.6 "$p3 send"
$ns at 1.7 "$p3 send"
$ns at 1.8 "$p3 send"
$ns at 1.9 "$p3 send"
$ns at 2.0 "$p3 send"
$ns at 2.1 "$p3 send"
$ns at 2.2 "$p3 send"
$ns at 2.3 "$p3 send"
$ns at 2.4 "$p3 send"
$ns at 2.5 "$p3 send"
$ns at 2.6 "$p3 send"
$ns at 2.7 "$p3 send"
$ns at 2.8 "$p3 send"
$ns at 2.9 "$p3 send"
$ns at 3.0 "finish"
$ns run
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk”

KMIT Page no:112


Department of CSE Computer Networks & Web Technologies Lab

extension)
BEGIN{
drop=0;
}
{
if($1= ="d" )
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);}
Steps for execution:
1) Open vi editor and type program. Program name should have the extension “ .tcl ”
[root@localhost~]# vi lab4.tcl
2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
3) Open vi editor and type awk program. Program name should have the extension “.awk ”
[root@localhost~]# vi lab4.awk
4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
5) Run the simulation program
[root@localhost~]# ns lab4.tcl
i) Here “ns” indicates network simulator. We get the topology shown in the
snapshot.
ii) Now press the play button in the simulation window and the simulation will
begins.
6) After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab4.awk lab4.tr
7) To see the trace file contents open the file as ,
[root@localhost~]# vi lab4.tr

KMIT Page no:113


Department of CSE Computer Networks & Web Technologies Lab

V Simulate to Compare Data Rate& Throughput.


(Simulate an Ethernet LAN using N nodes (6-10). Change error rate and data rate and compare
throughput.)
Code:

KMIT Page no:114


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:115


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:116


Department of CSE Computer Networks & Web Technologies Lab

This above output is for error rate 0.1. During next execution of simulation change error rate to 0.3,
0.5,….. and check its effect on throughput.

KMIT Page no:117


Department of CSE Computer Networks & Web Technologies Lab

vi Simulate to Plot Congestion for Different Source/Destination


(Aim: Simulate an Ethernet LAN using „n‟ nodes and set multiple traffic nodes and plot congestion
window for different source / destination)

KMIT Page no:118


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:119


Department of CSE Computer Networks & Web Technologies Lab

vii. Simulate to Determine the Performance with respect to Transmission of Packets


Aim: Simulate simple ESS and with transmitting nodes in wireless LAN by simulation and
determine the performance with respect to transmission of packets.

KMIT Page no:120


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:121


Department of CSE Computer Networks & Web Technologies Lab

OUTPUT:

KMIT Page no:122


Department of CSE Computer Networks & Web Technologies Lab

AIM:

1. Write a PHP script to print prime numbers between 1-50.


PROCEDURE:

<!DOCTYPE html>
<html>
<body>
<?php
$number = 1 ;
while ($number < 100 )
{
$div_count=0;
for ( $i=1;$i<=$number;$i++)
{
if (($number%$i)==0)
{
$div_count++;
}
}
if ($div_count<3)
{
echo $number." , ";
}
$number=$number+1;
}
?>
</body>
</html>

KMIT Page no:123


Department of CSE Computer Networks & Web Technologies Lab

Output:

KMIT Page no:124


Department of CSE Computer Networks & Web Technologies Lab

AIM:

2. PHP script to
a. Find the length of a string.
b. Count no of words in a string.
c. Reverse a string.
d. Search for a specific string.
PROCEDURE:

<!DOCTYPE html>
<html>
<body>
<?php

$x="keshav memorial institute of technology";


$searchword="memorial";

echo "String length is :"."&nbsp&nbsp".strlen($x);


echo "<br><br>";
echo "No.of words:" ."&nbsp&nbsp".str_word_count($x);
echo "<br><br>";
echo "Reverse String is:" . "&nbsp&nbsp".strrev($x);
echo "<br><br>";

//Search for a specific string

if(strpos($x, $searchword) !== false)


{
echo "Word Found!";
}
else
{
echo "Word Not Found!";
}

echo "<br><br>";

//finding string location


echo "String located at:"."&nbsp&nbsp".strpos($x, $searchword);
?>

KMIT Page no:125


Department of CSE Computer Networks & Web Technologies Lab

</body>
</html>

Output:

KMIT Page no:126


Department of CSE Computer Networks & Web Technologies Lab

AIM:

3. Write a PHP script to merge two arrays and sort them as numbers, in
descending order.

PROCEDURE:

<?php
// Function to merge array in sorted order

function sortedMerge($a, $b, $n, $m)


{
// Concatenate two arrays

$res = array();

$i = 0; $j = 0; $k = 0;
while ($i < $n)
{
$res[$k] = $a[$i];
$i += 1;
$k += 1;
}
while ($j < $m)
{
$res[$k] = $b[$j];
$j += 1;
$k += 1;
}
// sorting the res array in descending order

rsort($res);

echo "Sorted merged list :";

echo "<br>" ;

for ($i = 0; $i < count($res); $i++)

echo "index"."[".$i."]"."->".$res[$i] . "<br> ";


KMIT Page no:127
Department of CSE Computer Networks & Web Technologies Lab

// Driver code

$a = array( 10, 5, 15 );
$b = array( 20, 3, 2, 12 );
$n = count($a);
$m = count($b);

// Final merge list

sortedMerge($a, $b, $n, $m);

?>

Output:

KMIT Page no:128


Department of CSE Computer Networks & Web Technologies Lab

AIM:

4. Write a PHP script that reads data from one file and write into another
file.

PROCEDURE:

File name: “all.txt”

<?php

$f = file_get_contents("all.txt");

/*explode() function splits a string based on a string


delimeter, i.e. it splits the string wherever the delimeter
character occurs. This functions returns an array containing
the strings formed by splitting the original string.
*/

$f = explode(", ", $f);

function modFile($pos, $tothis, $inthis)


{

KMIT Page no:129


Department of CSE Computer Networks & Web Technologies Lab

foreach($inthis as $pos => $a)


{
}
$newarr = implode("\r\n", $inthis);

/*The implode function in PHP is used to "join elements of


an array with a string". The implode() function returns
a string from elements of an array.
It takes an array of strings and joins them together
into one string using a delimiter
(string to be used between the pieces) of your choice.
*/

$fh = fopen("example.txt", "w");


fwrite($fh, $newarr);
fclose($fh);
}
modFile(4, '', $f);

echo " data is available in new file or existed file";


?>

OUTPUT:

KMIT Page no:130


Department of CSE Computer Networks & Web Technologies Lab

Generated file name is “Example.txt”

KMIT Page no:131


Department of CSE Computer Networks & Web Technologies Lab

AIM:
5. Develop static pages (using Only HTML) of an online Book store. The
pages should resemble: www.amazon.com.The website should consists the
following pages.
a) Home page
b) Registration and user Login
c) User Profile Page
d) Books catalog
e) Shopping Cart
f) Payment By credit card
g) Order Conformation

PROCEDURE:

index.html:

<html>
<head>
<title>
Amazon</title>
</head>
<body bgcolor="lightblue"> <center>
<strong><h1>Welcome to AMAZON</h1></strong>
<form method="post" action="login.html" target=_blank >
<h4>for books</h4><input type="submit" value="click here">
</form>
</center>
</body>
</html>

KMIT Page no:132


Department of CSE Computer Networks & Web Technologies Lab

Login.html:

<html>
<head>
<title>
login page</title>
</head>
<body bgcolor="cyan"> <center>
<strong><h1> AMAZON </h1></strong></center>
<right>
<table align="right">
<tr>
<td><h4>user name</td>
<td><input type="text" ></td>
<td></td>
</tr>
<tr>
<td><h4>password</td>
<td><input type="password"></td>
<td></td>
</tr>
<tr>
<td>
KMIT Page no:133
Department of CSE Computer Networks & Web Technologies Lab

<form method="post" action="catalog.html" >


<input type="submit" value="submit" >
</form>
</td>
<td>
<form method="post" action="userpro.html" >
<input type="submit" value="register" >
&nbsp;&nbsp;
<input type="reset" value="reset"></form></td>
</tr>
</table>
</body>
</html>

Userpro.html:
<html>
<head>
<title>
login page</title>
</head>
<body bgcolor="cyan">
<center><strong><h1> AMAZON </h1></strong></center>
<form method="post" action="catalog.html" >
KMIT Page no:134
Department of CSE Computer Networks & Web Technologies Lab

<right>
<table align="left">
<tr>
<td><h4>user name</td>
<td><input type="text" ></td>
<tr>
<tr>
<td><h4>password</td>
<td><input type="password"></td>
</tr>
<tr>
<td><h4>confirm password</td>
<td><input type="password"></td>
</tr>
<tr>
<td><h4>male &nbsp;&nbsp;
<option >
<input type="radio" name="sex" id="male"></td>
<td><h4>female &nbsp; &nbsp;
<input type="radio" name="sex" id="female" ></td>
</option>
</tr>
<tr>
<td>Address</td>
<td><textarea name="address" rows=5 cols=19>
</textarea>
</td>
<tr>
<td>
<input type="submit" value="submit" ></td>
<td>
<input type="reset" value="reset"></td>
</tr>
</form>
</body>
</html>

KMIT Page no:135


Department of CSE Computer Networks & Web Technologies Lab

Catalog.html:

<html>
<head>
<title>
books catalog</title>
</head>
<body bgcolor="cyan">
<center><h1>AMAZON</h1></center>
<form method="post" action="shopping.html">
<left>
<table>
<tr>
<td><b><h3>frontend books</td>
<td></td></tr>
<tr>
<td></td>
<td><h4>C&Ds</td>
</tr>
<tr>
<td></td>
<td><h4>Ads</td>

KMIT Page no:136


Department of CSE Computer Networks & Web Technologies Lab

</tr>
<tr>
<td></td>
<td><h4>JAVA
</td></tr>
<tr>
<td><b><h3>backend books</td>
<td></td>
</tr>
<tr>
<td></td>
<td><h4>Oracle</td>
</tr>
<tr>
<td></td>
<td><h4>Ms SQL Server
</td></tr>
<tr>
<td></td>
<td><h4>MySql </td>
</tr>
</table>
</h4>
<center>
<b>for buy one of these books
<br>
</b><input type="submit" value="click here">
</center>
</form>
</body>
</html>

KMIT Page no:137


Department of CSE Computer Networks & Web Technologies Lab

Shopping.html:

<html>
<head><title>shopping cart</title>
</head>
<body bgcolor="cyan">
<center><h1>
Shopping Cart</h1></center>
<br><br><br><br><br>
<table align="center">
<tr>
<td>Text Books</td>
<td>
<select >
<optgroup label="select the book">
<option value="C&Ds">C&Ds
<option value="Ads">Ads
<option value="Java">Java
<option value="Oracle">Oracle
<option value="Ms SQL Server">Ms SQL Server
<option value="MySql">MySql
</optgroup>

KMIT Page no:138


Department of CSE Computer Networks & Web Technologies Lab

</select>
</td></tr>
<tr>
<td>
Quantity</td>
<td>
<input type="text" id="q">
</td></tr>
<tr>
<td></td>
<td>
<form method=post action="payment.html">
<input type="submit" value=ok />
</form>
</td></tr>
</table>
<center>
<pre>Cost of one book is"500" + shipping "100"</pre>
</center>
<body>
</html>

KMIT Page no:139


Department of CSE Computer Networks & Web Technologies Lab

payment.html:
<html>
<head><title>payment</title></head>
<body bgcolor="cyan">
<center><h1>Payment By Credit Card</h1></center>
<form method=post action="ordrconform.html">
<br><br><br><br><br>
<table align="center">
<tr><td>
<h4>Total Amount</h4></td>
<td><input type="text">
</td>
</tr><tr>
<td><h4>Credit Card Number</td>
<td><input type="text"></td>
</tr>
<tr><td>
</td>
<td><input type="submit" value=OK>
</td>
</tr>
</table>
</form></body></html>

KMIT Page no:140


Department of CSE Computer Networks & Web Technologies Lab

Orderconfrom.html:

<html>
<head><title>order conformation</title><M/head>
<body bgcolor="cyan">
<center>
<h1><b>BOOK SHOPPING</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre>
<h2><b>THANK YOU</h2>
</center>
</body></html>

KMIT Page no:141


Department of CSE Computer Networks & Web Technologies Lab

AIM:

6. Validate the Registration, user login, user profile and payment by credit
card pages using JavaScript.

PROCEDURE:

index.html:

<html>
<frameset rows="25%,*">
<frame src="top.html" name="top" scrolling ="no" frameborder ="0">
<frameset cols="25%,75%">
<frame src="left.html" name="left" scrolling ="no" frameborder ="0">
<frame src="right.html" name="right" scrolling ="auto" frameborder ="0">
</frameset>
</frameset>
</html>

left.html:

<html>
<body bgcolor="pink">
<h3>
<ul>
<li><a href="login.html" target="right"><font color="black">
LOGIN</font></a></li><br><br>
<li><a href="profile.html" target="right"><font color="black">
USER PROFILE</font></a></li><br><br>
<li><a href="catalog.html" target="right"><font color="black">
BOOKS CATALOG</font></a></li><br><br>
<li><a href="scart.html" target="right"><font color="black">
SHOPPINGCART</font></a></li><br><br>
<li><a href="payment.html" target="right"><font color="black">
PAYMENT</font></a></li><br><br>
<br><br>
</ul>
</body>
</html>

KMIT Page no:142


Department of CSE Computer Networks & Web Technologies Lab

top.html:

<html>
<body bgcolor="pink">
<br><br>
<marquee><h1 align=”center”><b><u>ONLINE BOOK
STORAGE</u></b></h1></marquee>
</body>
</html>

right.html:

<html>
<body>
<br><br><br><br><br>
<h2 align="center">
<b><p> welcome to online book storage. Press login if you are
having id otherwise press registration.
</p></b></h2>
</body>
</html>

KMIT Page no:143


Department of CSE Computer Networks & Web Technologies Lab

profile.html:
<html>
<body bgcolor="pink"><br><br>
<script type="text/javascript">
function validate()
{
var flag=1;
if(document.myform.name.value==""||
document.myform.addr.value==""||
document.myform.phno.value==""||
document.myform.id.value==""||
document.myform.pwd.value=="")
{
alert("Enter all the details");
flag=0;
}
var str=document.myform.phno.value;
var x=new RegExp("\\d","g");
if(!(str.match(x)))
{
if(!(str.length==10))
flag=0;
}
var str1=document.myform.id.value;
var x1=new RegExp("^[A-Z][a-zA-Z]+$","g");
if(!(str1.match(x1)))
{
flag=0;
alert("Invalid UserID");
}
var str1=document.myform.pwd.value;
var x1=new RegExp("^[A-Z][a-zA-Z]+$","g");
if(!(str1.match(x1)))
{
flag=0;
alert("Invalid password");
}
if(flag==1)
{
alert("VALID INPUT");
KMIT Page no:144
Department of CSE Computer Networks & Web Technologies Lab

window.self.location.href="login.html";
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}}
</script>
<form name="myform">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="type" name="addr"><br>
CONTACT NUMBER:<input type="text" name="phno"><br>
LOGINID :<input type="text" name="id"><br>
PASSWORD :<input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="button" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear">
</form></body></html>

KMIT Page no:145


Department of CSE Computer Networks & Web Technologies Lab

login.html:

<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.pwd.value=="")
{
alert("LoginId and Password must be filled")
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
window.open("catalog.html","right");
} else
{ alert("INVALID INPUT");
//document.myform.focus();
}}
</script>
<form name="myform">
<div align="center"><pre>
LOGIN ID:<input type="text" name="id"><br>
PASSWORD:<input type="password" name="pwd"><br><br>
</pre>
<input type="button" value="ok"
onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</div>
</form>
</body>
</html>

KMIT Page no:146


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:147


Department of CSE Computer Networks & Web Technologies Lab

catalog.html:

<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.title.value==""||
document.myform.no.value==""||
document.myform.cost.value=="")
{
flag=0;
}
str=document.myform.title.value;
var str1=document.myform.cost.value;
if(!((str=="c"&& str1==444) || (str=="jsp" && str1==555)))
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform" action="scart.html" target="right">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
TITLE :<input type="text" name="title"><br>
NO.OF BOOKS :<input type="text" name="no"><br>
COST OF BOOK :<input type="text"name="cost"><br>
</pre><br><br>

KMIT Page no:148


Department of CSE Computer Networks & Web Technologies Lab

</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">
&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear">
</form>
</body>
</html>

scart.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.title.value=="")
{
flag=0;
}
str=document.myform.title.value;
if(str=="c"||str=="C")
{

KMIT Page no:149


Department of CSE Computer Networks & Web Technologies Lab

document.myform.t1.value="C";
document.myform.t2.value=444;
}
else if(str=="jsp"||str=="JSP")
{
document.myform.t1.value="JSP";
document.myform.t2.value=555;
}
else
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}}
</script>
<form name="myform" action="payment.html" target="right">
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title"><br>
</pre><br><br>

Book Cost: <input type="text" name="t2" >


</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear">
<input type="submit" value="Purchase">
</form>
</body>
</html>

KMIT Page no:150


Department of CSE Computer Networks & Web Technologies Lab

payment.html:
html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""|| document.myform.pwd.value==""||
document.myform.amount.value==""|| document.myform.num.value=="")
{
flag=0;
}
var str=document.myform.amount.value;
var x=new RegExp("\\d","g");
if(!(str.match(x)))
{ flag=0;
}
var str1=document.myform.num.value;
var x1=new RegExp("\\d","g");
if(!(str.match(x1)))

KMIT Page no:151


Department of CSE Computer Networks & Web Technologies Lab

{ flag=0;
}i
f(flag==1)
{ alert("VALID INPUT");
window.self.location.href="order.html";
} else
{
alert("INVALID INPUT");
document.myform.focus();
}}
</script>
<form name="myform" >
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD :<input type="password" name="pwd"><br>
AMOUNT :<input type="text" name="amount"><br>
CREDITCARDNUMBER :<input type="PASSWORD"
name="num"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="button" value="ok"
onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>

KMIT Page no:152


Department of CSE Computer Networks & Web Technologies Lab

order.html
<html>
<head><title>order conformation</title><M/head>
<body bgcolor="cyan">
<center>
<h1><b>AMAZON</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre>
<h2><b>THANK YOU</h2>
</center>
</body>
</html>

KMIT Page no:153


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:154


Department of CSE Computer Networks & Web Technologies Lab

AIM:

7. Create and save an XML document on the server, which contains 10 users
information. Write a program, which takes User Id as an input and returns
the user details by taking the user information from the XML document.

Generating xml file:

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class DomParserDemo


{

public static void main(String[] args) throws Exception


{

//design patterns: 3 types:creational,structural,behavioral patterns


//in creational ->factory patern-> generate the DOM Object.
// here Document builder getting DOM object and creating a new
Document.
// newInstance it will return the instance for a factory pattern.
// using factory object'f' then u will be able to create DOM object.
//this is the factory for Document builder.
//DocumentBuilder creates a document object.

DocumentBuilderFactory f =
DocumentBuilderFactory.newInstance();

DocumentBuilder b= f.newDocumentBuilder();

Document doc =b.newDocument();

Element rootele = doc.createElement("students");


Element stuele = doc.createElement("student");
Element nameele = doc.createElement("name");
KMIT Page no:155
Department of CSE Computer Networks & Web Technologies Lab

Element emailele = doc.createElement("email");


Element mobilele = doc.createElement("mobile");
Element addrele = doc.createElement("address");

Text t1=doc.createTextNode("xxx");
Text t2=doc.createTextNode("[email protected]");
Text t3=doc.createTextNode("1234567899");
Text t4=doc.createTextNode("Hyderabad");

nameele.appendChild(t1);
emailele.appendChild(t2);
mobilele.appendChild(t3);
addrele.appendChild(t4);

stuele.appendChild(nameele);
stuele.appendChild(emailele);
stuele.appendChild(mobilele);
stuele.appendChild(addrele);

rootele.appendChild(stuele);
doc.appendChild(rootele);

//transform () method is used to convert the document object to XML File

Transformer t=TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(doc),new StreamResult(new
FileOutputStream("g:/student.xml")));
System.out.println("xml file generated");
}
}

KMIT Page no:156


Department of CSE Computer Networks & Web Technologies Lab

Staff.xml:

<?xml version = "1.0"?>

<company>
<staff id = "393">
<firstname>yong</firstname>
<lastname>mookkim</lastname>
<nickname>mykong</nickname>
<salary>100000</salary>
</staff>

<staff id = "487">
<firstname>low</firstname>
<lastname>yien</lastname>
<nickname>yienfong</nickname>
<salary>95000</salary>
</staff>

KMIT Page no:157


Department of CSE Computer Networks & Web Technologies Lab

<staff id = "488">
<firstname>low</firstname>
<lastname>yien</lastname>
<nickname>fong</nickname>
<salary>9000</salary>
</staff>

<staff id = "489">
<firstname>xxx</firstname>
<lastname>yien</lastname>
<nickname>yienfong</nickname>
<salary>5000</salary>
</staff>
<staff id = "490">
<firstname>yyy</firstname>
<lastname>yien</lastname>
<nickname>yienfong</nickname>
<salary>956000</salary>
</staff>
<staff id = "491">
<firstname>zzz</firstname>
<lastname>yien</lastname>
<nickname>yienfong</nickname>
<salary>55000</salary>
</staff>
<staff id = "492">
<firstname>aaa</firstname>
<lastname>bbb</lastname>
<nickname>yienfong</nickname>
<salary>95600</salary>
</staff>
<staff id = "493">
<firstname>bbb</firstname>
<lastname>ayann</lastname>
<nickname>yienfong</nickname>
<salary>960000</salary>
</staff>
<staff id = "494">
<firstname>ccc </firstname>
<lastname>yann</lastname>
KMIT Page no:158
Department of CSE Computer Networks & Web Technologies Lab

<nickname>yienfong</nickname>
<salary>58000</salary>
</staff>
<staff id = "495">
<firstname>ddd</firstname>
<lastname>eee</lastname>
<nickname>fong</nickname>
<salary>85000</salary>
</staff>

</company>

File name : Readxmlfiledata.java

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class Readxmlfiledata


{
public static void main(String args[])
{
try
{
File fxmlfile = new File("g:/staff.xml");

//Create a DocumentBuilder
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

//Create a Document from a file or stream

Document doc = dBuilder.parse(fxmlfile);

KMIT Page no:159


Department of CSE Computer Networks & Web Technologies Lab

//Extract the root element

doc.getDocumentElement().normalize();

//getNodeName():returns the name of the current node

System.out.println("Root element :" +


doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("staff");

System.out.println(" ---------------------------- "+nList.getLength());

for (int temp = 0; temp < nList.getLength(); temp++)


{
Node nNode = nList.item(temp);

System.out.println("\nCurrent Element :" +


nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
//Examine attributes and returns specific attribute
System.out.println("Staff id : " + eElement.getAttribute("id"));

//getElementsByTagName("subelementName"): returns a
list of subelements of specified name

System.out.println("First Name : " +


eElement.getElementsByTagName("firstname").item(0).getTextContent())
;
System.out.println("Last Name : " +
eElement.getElementsByTagName("lastname").item(0).getTextContent());

KMIT Page no:160


Department of CSE Computer Networks & Web Technologies Lab

System.out.println("Nick Name : " +


eElement.getElementsByTagName("nickname").item(0).getTextContent())
;
System.out.println("Salary :"+
eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:

KMIT Page no:161


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:162


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:163


Department of CSE Computer Networks & Web Technologies Lab

AIM:

8. Install TOMCAT web server. Convert the static web pages of assignments
2 into dynamic webpages using servlets and cookies. Hint: Users
information (user id, password, credit card number) would be stored in
web.xml. Each user should have a separate Shopping Cart.

PROCEDURE:

 First install the tomcat into the system.


 Then make a subdirectly(eg., tr) in the \tomcat\webapps.
 Under tr create WEB-INF directory and also place the html files in this tr
directory only.
 Next under WEB-INF create two subclasses lib,classes and web.xml
 Next place all the class files under the classes and jar files(servlet-
api.jar,classes12.jar etc…) under lib
 subdirectories.
 After this start tomcat by giving the following command at the
instll_dir>tomcat>bin
 Catalina.bat run
 At the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or
servlet url pattern
 Portno 8080 is assigned for the tomcat.

Web.xml:

<?xml version="1.0" encoding="iso-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Servlet 2.4 Examples</display-name>
<description>
Servlet 2.4 Examples.
</description>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>reg</servlet-class>
</servlet>

KMIT Page no:164


Department of CSE Computer Networks & Web Technologies Lab

<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet>
<servlet-name>profile</servlet-name>
<servlet-class>profile</servlet-class>
</servlet>
<servlet>
<servlet-name>catalog</servlet-name>
<servlet-class>catalog</servlet-class>
<servlet-mapping>
<servlet-name>order</servlet-name>
<url-p</servlet>
<servlet>
<servlet-name>order</servlet-name>
<servlet-class>order</servlet-class>
</servlet>
attern>order</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>catalog</servlet-name>
<url-pattern>catalog</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>profile</servlet-name>
<url-pattern>profile</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>reg</url-pattern>
</servlet-mapping>
</web-app>

KMIT Page no:165


Department of CSE Computer Networks & Web Technologies Lab

Main.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink">
<br /><br /><br /><br /><br />
<h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><br /><br /><br
/>
<h2 align="center"><pre>
<b>Welcome to online book storage.
Press LOGIN if you are having id
otherwise press REGISTRATION
</b></pre></h2>
<br /><br /><pre>
<div align="center"><a href="/tr/login.html">LOGIN</a> <a href="/tr/reg.html">
REGISTRATION</a></div></pre>
</body>
</html>

Login.html:

<html>
<body bgcolor="pink"><br /><br /><br />
<form name="myform" method="post" action="/tr/login">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

KMIT Page no:166


Department of CSE Computer Networks & Web Technologies Lab

Reg.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br />
<form name="myform" method="post" action="/tr/reg">
<div align="center"><pre>
NAME :<input type="text" name="name" /><br />
ADDRESS :<input type="text" name="addr" /><br />
CONTACT NUMBER :<input type="text" name="phno" /><br />
LOGINID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Profile.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br /><br />
<form name="myform" method="post" action="/tr/profile">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div></form></body></html>

KMIT Page no:167


Department of CSE Computer Networks & Web Technologies Lab

Catalog.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br /><br />
<form method="post" action="/tr/catalog">
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok"
name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body>
</html>

Order.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br />
<form method="post" action="/tr/reg">
<div align="center"><pre>
NAME :<input type="text" name="name" /><br />
PASSWORD :<input type="password" name="pwd" />
TITLE :<input type="text" name="title" /><br />
NO. OF BOOKS :<input type="text" name="no" /><br />
DATE :<input type="text" name="date" /><br />
CREDIT CARD NUMBER:<input type="password" name="cno" /><br
/></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" name="button1"/>

KMIT Page no:168


Department of CSE Computer Networks & Web Technologies Lab

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear"


name="button2"/>
</div>
</form>
</body>
</html>

Login.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{ PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
try
{ Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott
","tiger")
;
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
KMIT Page no:169
Department of CSE Computer Networks & Web Technologies Lab

if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\"/tr/login.html\">press LOGIN to RETRY</a>");
}
else
{
pw.println("VALID LOGIN ID<br><br>");
pw.println("<h3><ul>");
pw.println("<li><ahref=\"profile.html\"><fontcolor=\"black\">USER
PROFILE</font> </a></li><br><br>");
pw.println("<li><ahref=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>");
pw.println("<li><ahref=\"order.html\"><fontcolor=\"black\">ORDER
CONFIRMATION</font> </a></li><br><br>");
}
pw.println("</body></html>");
}
catch(Exception e)
{ resp.sendError(500,e.toString());
}
}

Reg.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Reg extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String name=req.getParamenter("name");
String addr=req.getParameter("addr");
String phno=req.getParameter("phno");
String id=req.getParamenter("id");
KMIT Page no:170
Department of CSE Computer Networks & Web Technologies Lab

String pwd=req.getParameter("pwd");
int no=Integer.parseInt(phno);
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott
","tiger")
;
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}}
if(flag==1)
{
pw.println("SORRY INVALID ID ALREADY EXITS TRY AGAIN WITH NEW
ID<br><br>");
pw.println("<a href=\"/tr/reg.html\">press REGISTER to RETRY</a>");
}
else
{ Statement stmt1=con.createStatement();
stmt1.executeUpdate("insertintologin
values("+names","+addr+","+no+","+id+","+pwd+")");
pw.println("YOUR DETAILS ARE ENTERED<br><br>");
pw.println("<a href=\"/tr/login.html\">press LOGIN to login</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
KMIT Page no:171
Department of CSE Computer Networks & Web Technologies Lab

Catlog.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Catalog extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String title=req.getParameter("title");
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott
","tiger")
;
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
pw.println(",div align=\"center\">");
pw.println("TITLE :"+rs.getString(1)+"<br>");
pw.println("AUTHOR :"+rs.getString(2)+"<br>");
pw.println("VERSION :"+rs.getString(3)+"<br>");
pw.println("PUBLISHER :"+rs.getString(4)+"<br>");
pw.println("COST :"+rs.getString(5)+"<br>");
pw.println("</div");
flag=1;
}
if(flag==0)
KMIT Page no:172
Department of CSE Computer Networks & Web Technologies Lab

{
pw.println("SORRY INVALID TITLE TRY AGAIN <br><br>");
pw.println("<a href=\"/tr/catalog.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Profile.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Profile extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection con=DriverManager.getConnection("jdbc:oracle:thin:
@localhost:1521:orcl","scott","tiger");
Statement stmt=con.createStatement();
String sqlstmt="select * from login where id="+id+"";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
pw.println("<br><br><br>");
while(rs.next())

KMIT Page no:173


Department of CSE Computer Networks & Web Technologies Lab

{
pw.println("<div align=\"center\">");
pw.println("NAME :"+rs.getString(1)+"<br>");
pw.println("ADDRESS :"+rs.getString(2)+"<br>");
pw.println("PHONE NO :"+rs.getString(3)+"<br>");
pw.println("</div>");
flag=1;
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\"/tr/profile.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Order.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
String title=req.getParameter("title");
String count1=req.getParameter("no");
String date=req.getParameter("date");
KMIT Page no:174
Department of CSE Computer Networks & Web Technologies Lab

String cno=req.getParameter("cno");
int count=Integer.parseInt(count1);
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott
","tiger")
;
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");
}
else
{
Statement stmt2=con.createStatement();
String s="select cost from book where title="+title+"";
ResultSet rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next())
{
flag1=1;
x=Integer.parseInt(rs1.getString(1));
count*x;
pw.println("AMOUNT :"+amount+"<br><br><br><br>");
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insertintodetails
KMIT Page no:175
Department of CSE Computer Networks & Web Technologies Lab

values('"+id+",'"+title+"'+amount+'","'+cno+'")"');
pw.println("YOUR ORDER has taken<br>");
}
if(flag1==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");
}
}
pw.println("</body></html>");
con.close();
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}

KMIT Page no:176


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:177


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:178


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:179


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:180


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:181


Department of CSE Computer Networks & Web Technologies Lab

AIM:
9. Redo the previous task using JSP by converting the static web pages of
assignments 2 into dynamic web pages. Create a database with user
information and books information and books information. The books
catalogue should be dynamically loaded from the database. Follow the
MVC architecture while doing the website.

PROCEDURE:

1) Create your own directory under tomcat/webapps (e.g. tr1)


2) Copy the html files in tr1
3) Copy the jsp files also into tr1
4) Start tomcat give the following command
Catalina.bat run
At install‐dir/bin
5) at I.E give url as http://localhost:8081/tr1/main.html

Main.html:

<html>
<body bgcolor=”pink”>
<br><br><br><br><br><br>
<h1 align=”center”>>U>ONLINE BOOK STORAGE</u></h1><br><br><br>
<h2 align=”center”><PRE>
<b> Welcome to online book storage.
Press LOGIN if you are having id
Otherwise press REGISTRATION
</b></PRE></h2>
<br><br><pre>
<div align=”center”><a href=”/tr/login.html”>LOGIN</a>
href=”/tr/login.html”>REGISTRATION</a></div></pre>
</body></html>

KMIT Page no:182


Department of CSE Computer Networks & Web Technologies Lab

Login.html:
<html>
<body bgcolor=”pink”><br><br><br>
<form name="myform" method="post" action=/tr1/login.jsp">
<div align="center"><pre>
LOGIN ID : <input type="passwors" name="pwd"></pre><br><br>
PASSWORD : <input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>

Reg.html:

<html>
<body bgcolor="pink"><br><br>
<form name="myform" method="post" action="/tr1/reg.jsp">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="text" name="addr"><br>
CONTACT NUMBER : <input type="text" name="phno"><br>
LOGIN ID : <input type="text" name="id"><br>
PASSWORD : <input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>

KMIT Page no:183


Department of CSE Computer Networks & Web Technologies Lab

Profile.html:

<html>
<body bgcolor="pink"><br><br>
<form name="myform" method="post" action="/tr1/profile.jsp">
<div align="center"><pre>
LOGIN ID : <input type="text" name="id"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>

Catalog.html:

<html>
<body bgcolor="pink"><br><br><br>
<form method="post" action="/tr1/catalog.jsp">
<div align="center"><pre>
BOOK TITLE : <input type="text" name="title"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
name=”button1”>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<inputtype="reset"value="c
lear" name=”button2”>
</form>
</body>
</html>

KMIT Page no:184


Department of CSE Computer Networks & Web Technologies Lab

Order.html:

<html>
<body bgcolor="pink"><br><br><br>
<form method="post" action="/tr1/order.jsp">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD : <input type="password" name="pwd"><br>
TITLE :<input type="text" name="title"><br>
NO. OF BOOKS : <input type="text" name="no"><br>
DATE : <input type="text" name="date"><br>
CREDIT CARD NUMBER : <input type="password"
name="cno"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok"
name=”button1”>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear" name=”button2”>
</form>
</body>
</html>

Login.jsp:

%@page import=”java.sql.*”%
%@page import=”java.io.*”%
<%
out.println(“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter(“id”);
String pwd=request.getParameter(“pwd”);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott
”,”tiger”);
Statement stmt=con.createStatement();
String sqlstmt=”select id,password from login where id=”+id+” and
password=”+pwd+””;
ResultSet rs=stmt.executeQuery(sqlstmt);
KMIT Page no:185
Department of CSE Computer Networks & Web Technologies Lab

int flag=0;
while(rs.next())
{
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID<br><br>”);
out.println(“ <a href=\”/tr1/login.html\”>press LOGIN to RETRY</a>”);
}
else
{
out.println(“VALID LOGIN ID<br><br>”);
out.println(“<h3><ul>”);
out.println(“<li><ahref=\”profile.html\”><fontcolor=\”black\”>USER
PROFILE</font></a></li><br><br>”);
out.println(“<li><ahref=\”catalog.html\”><fontcolor=\”black\”>BOOKS
CATALOG</font></a></li><br><br>”);
out.println(“<li><ahref=\”order.html\”><fontcolor=\”black\”>ORDER
CONFIRMATION</font></a></li><br><br>”);
out.println(“</ul>”);
}
out.println(“<body></html>”);
%>

Reg.jsp:

%@page import=”java.sql.*”%
%@page import=”java.io.*”%
<%
out.println(“<html><body bgcolor=\”pink\”>”);
String name=request.getParameter(“name”);
String addr=request.getParameter(“addr”);
String phno=request.getParameter(“phno”);
String id=request.getParameter(“id”);
String pwd=request.getParameter(“pwd”);
int no=Integer.parseInt(phno);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection con=
KMIT Page no:186
Department of CSE Computer Networks & Web Technologies Lab

DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement();
String sqlstmt=”select id from login”;
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equals(rs.getString(1)))
{
flag=1;
}
}
if(flag==1)
{
out.println(“SORRY LOGIN ID ALREADY EXISTS TRY AGAIN WITH NEW
ID <br><br>”);
out.println(“<a href=\”/tr1/reg.html\”>press REGISTER to RETRY</a>”);
}
else
{
Statement stmt1=con.createStatement ();
stmt1.executeUpdate (“insert into login values
(“+name+”,”+addr+”,”+no+”,”+id+”,”+pwd+”)”);
out.println (“YOU DETAILS ARE ENTERED <br><br>”);
out.println (“<a href =\”/tr1/login.html\”>press LOGIN to login</a>”);
}
out.println (“</body></html>”);
%>

Profile.jsp:

<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
KMIT Page no:187
Department of CSE Computer Networks & Web Technologies Lab

out.println (“<html><body bgcolor=\”pink\”>”);


String id=request.getParameter(“id”);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.regiserDriver(d);
Connection con=
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select * from login where id=”+id+””;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0;
while(rs.next())
{
out.println (“<div align=\”center\”>”);
out.println (“NAME :”+rs.getString(1)+”<br>”);
out.println (“ADDRESS :”+rs.getString(2)+”<br>”);
out.println (“PHONE NO :”+rs.getString(3)+”<br>”);
out.println (“</div>”);
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/profile.html\”>press HERE to RETRY </a>”);
}
out.println (“</body></html>”);
%>

KMIT Page no:188


Department of CSE Computer Networks & Web Technologies Lab

Catalog.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String title=request.getParameter (“title”);
Driver d=new oracle.jdbc.driver.OracleDriver ();
DriverManager.regiserDriver (d);
Connection con=
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select * from book where title=”+title+””;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0;
while(rs.next())
{
out.println (“<div align=\”center\”>”);
out.println (“TITLE :”+rs.getString(1)+”<br>”);
out.println (“AUTHOR :”+rs.getString(2)+”<br>”);
out.println (“VERSION:”+rs.getString(3)+”<br>”);
out.println (“PUBLISHER :” +rs.getString(4)+”<br>”);
out.println (“COST :” +rs.getString(5)+”<br>”);
out.println (“</div>”);
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/catalog.html\”>press HERE to RETRY </a>”);
}
out.println (“</body></html>”);
%>

KMIT Page no:189


Department of CSE Computer Networks & Web Technologies Lab

Order.jsp:

<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter (“id”);
String pwd=request.getParameter (“pwd”);
String title=request.getParameter (“title”);
String count1=request.getParameter (“no”);
String date=request.getParameter (“date”);
String cno=request.getParameter (“cno”);
int count=Integer.parseInt(count1);
Driver d=new oracle.jdbc.driver.OracleDriver ();
DriverManager.regiserDriver (d);
Connection con=
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select id, password from login”;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&& pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY </a>”);
}
else
{
Statement stmt2=con.createStatement();
String s=”select cost from book where title=”+title+””;
ResultSet rs1=stmt2.executeQuery(s);
int flag1=0;
KMIT Page no:190
Department of CSE Computer Networks & Web Technologies Lab

while(rs1.next())
{
flag1=1;
x=Integer.parseInt(rs1.getString(1));
amount=count*x;
out.println(“AMOUNT :”+amount+”<br><br><br><br>”);
Statement stmt1=con.createStatement ();
stmt1.executeUpdate (“insert into details
(“+id+”,”+title+”,”+amount+”,”+date+”,”+cno+”)”);
out.println (“YOU ORDER HAS TAKEN<br>”);
}
if(flag1==0)
{
out.println(“SORRY INVALID BOOK TRY AGAIN <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY </a>”);
}
} out.println (“</body></html>”);%>
}

KMIT Page no:191


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:192


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:193


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:194


Department of CSE Computer Networks & Web Technologies Lab

KMIT Page no:195

You might also like