CN - WT Cse Lab Manual
CN - WT Cse Lab Manual
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
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
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.
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
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
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.
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.
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++)
{
t[p++]=a[q];
}
t[p]='\0';
strcat(fs,t);
}
strcat(fs,"01111110");
printf("After stuffing : %s",fs);
getch();
}
Output:
Enter bit string: 10101111110
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
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.
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();
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
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)
{
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)
{
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
10100000110001100
10001000000100001
1010001101011010
crc is 1010001101011010
10001000000100001 ) 110111010001101011010 (
10001000000100001
10101010000101001
10001000000100001
10001000000100001
10001000000100001
00000000000000000
-------------------------- Data transferred correctly
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';
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;
}
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);
}
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
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)
{
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)
{
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
10001000000100001
1010001101011010
crc is 1010001101011010
10001000000100001) 110111010001101011010 (
10001000000100001
10101010000101001
10001000000100001
10001000000100001
10001000000100001
00000000000000000
-------------------------- Data transferred correctly
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");
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
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;
}
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.
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)
{
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
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 ");
for(i=1;i<=5;i++)
{
printf("--> %d",path[index][i]);
if(path[index][i]==ed)
break;
} getch(); }
Output:
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]);
}
}
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)
{
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];
}
}
}
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++)
{
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++)
{
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
enter no of nodes3
enter the adjacency matrix
012
105
250
enter the source for broadcasting2
given adjacency matrix is
012
105
250
25
1
2
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
785
2 sends message to 1
2 sends message to 3
1 sends message to 0
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++)
{
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)
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
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
30 I
18 H
12 H
10 I
J
32 A
21 H
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;
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
#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)
{
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:
}
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);
}}
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
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.
Note: The AirPcap has been discontinued by RiverBed and is 802.11n only.
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.
Two different methods for starting Wireshark are available. These include the Start menu and the
Run command 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.
To open the Capture Interfaces dialog box using the Capture menu:
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.
To open the Capture Interfaces dialog box using the Capture interfaces keyboard shortcut:
1. Press <Ctrl> + I.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Topology - This shows the traceroute for the scan you performed. You can see how many hops
your data goes through to reach the target.
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.
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:
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.
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
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.
Mac OS X - Open the Terminal application located in the Utility subfolder of your Applications folder.
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.
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.
-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.
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.
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.
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.
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:
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.
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:
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.
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.
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.
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
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
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)
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
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)
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:
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
OUTPUT:
ns filename.tcl
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 .
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 .
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) .
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 .
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) .
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)
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
}
$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"
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
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.
OUTPUT:
AIM:
<!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>
Output:
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
echo "<br><br>";
</body>
</html>
Output:
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
$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 "<br>" ;
// Driver code
$a = array( 10, 5, 15 );
$b = array( 20, 3, 2, 12 );
$n = count($a);
$m = count($b);
?>
Output:
AIM:
4. Write a PHP script that reads data from one file and write into another
file.
PROCEDURE:
<?php
$f = file_get_contents("all.txt");
OUTPUT:
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>
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
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
<option >
<input type="radio" name="sex" id="male"></td>
<td><h4>female
<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>
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>
</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>
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>
</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>
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>
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>
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>
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>
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()">
<input type="reset" value="clear">
</form></body></html>
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()">
<input type="reset" value="clear" >
</div>
</form>
</body>
</html>
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>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">
<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")
{
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>
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)))
{ 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()">
<input type="reset" value="clear" >
</form>
</body>
</html>
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>
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.
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.*;
DocumentBuilderFactory f =
DocumentBuilderFactory.newInstance();
DocumentBuilder b= f.newDocumentBuilder();
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);
Transformer t=TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(doc),new StreamResult(new
FileOutputStream("g:/student.xml")));
System.out.println("xml file generated");
}
}
Staff.xml:
<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>
<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>
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;
//Create a DocumentBuilder
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
doc.getDocumentElement().normalize();
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
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:
Web.xml:
<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>
Main.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()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>
Reg.html:
Profile.html:
Catalog.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"/>
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())
{
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());
}
}
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:
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>
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()"> <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()">()"> <input type="reset"
value="clear">
</form>
</body>
</html>
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()">()"> <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”> <inputtype="reset"value="c
lear" name=”button2”>
</form>
</body>
</html>
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”> <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
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>”);
%>
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>”);%>
}