You are on page 1of 69

CHALAPATHI INSTITUTE OF TECHNOLOGY

Experiment - I
Aim:
To construct a Decision tree.
Description:
Suppose we have some data and we want to build a decision tree from the data.
First, we need to prepare the data then fire up explorer and load in the data. Next, we select a decision
tree construction method. Build a tree and interpret the output.
Input:
Prepare the data as follows:
outlook

temperature

humidity

windy

play

overcast
sunny
overcast
rainy
rainy
rainy
overcast
sunny
sunny
rainy
sunny
overcast
overcast
rainy

85
80
83
70
68
65
64
72
69
75
75
72
81
71

85
90
86
96
80
70
65
95
70
80
80
90
75
91

FALSE
TRUE
FALSE
FALSE
FALSE
TRUE
TRUE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
TRUE

no
no
yes
yes
yes
no
yes
no
yes
yes
yes
yes
yes
no

Save this book.csv and open csv (cmd delimited).Load the data into Explorer

CHALAPATHI INSTITUTE OF TECHNOLOGY

Lets load the data into Explorer and start analyzing. Pick up WEKA to get the panel shown below.
Click on Applications Menu.

Select Explorer option. The Explorer screen will be shown below:


2

CHALAPATHI INSTITUTE OF TECHNOLOGY

In the Explorer screen 6 tabs along with the top are the basic operations that the explorer supports.
Right now, we are on the Preprocess tab.
Preprocess:
Choose the data set and modify it in various ways.
Classify:
Train learning schemes that perform classification, regression & evaluate them.
Cluster:
Learn clusters for the dataset.
Association:
Learn association rules for data and evaluate them.

CHALAPATHI INSTITUTE OF TECHNOLOGY


Select Attribute:
Select most relevant aspects in the dataset.
Visualize:
View different 2-dimensional plots of the data & interact with them.
Classify:
First, select the classify tab in the explorer. Then choose button at the top left of the opening
tree section of the hierarchical menu shown below. The menu structure represents the organization of
WEKA code into modules.
Click on Open file, Select appropriate data file. The Explorer having the loaded file, the screen will
be as shown below.

suppose the open file is weather.arff.


4

CHALAPATHI INSTITUTE OF TECHNOLOGY

This tells you about the datasets. It has 14 instances and 5 attributes.
The attributes are :
Outlook
Temperature
Humidity
Windy
Play
The first attribute outlook is selected by default. It has no missing values.
The actual values are sunny, overcast, rainy and they occur 5, 4, 5 times respectively.
A histogram at the lower right shows how often each of the 2 values of the class outlook which is
as shown in above figure.

CHALAPATHI INSTITUTE OF TECHNOLOGY


J48 appears in the line beside the choose button as shown in the figure below:

If you click the line GUI, generic object editor is displayed. Having classify as the button.
Click on the start button.
Examining the output:
The figure below shows the output. At the beginning is a summary of the dataset and the
fact that 10-fold cross-validation is used to evaluate it. Then comes a pruned decision-tree in textual
form. The first split is on the outlook attribute and then second level. The splits are on humidity, windy
respectively. In the tree structure a colon introduced a class that has been assigned, designed a particular
leaf followed by the number of instances that reach the leaf.

CHALAPATHI INSTITUTE OF TECHNOLOGY

Classifier Output:
By clicking the start button the output is as follows:
=== Run information ===
Scheme:
weka.classifiers.trees.J48 -C 0.25 -M 2
Relation: weather
Instances: 14
Attributes: 5
outlook
temperature
humidity
windy
play
Test mode: 10-fold cross-validation

CHALAPATHI INSTITUTE OF TECHNOLOGY


=== Classifier model (full training set) ===
J48 pruned tree
-----------------outlook = sunny
|humidity <= 75: yes (2.0)
humidity > 75: no (3.0)
outlook = overcast: yes (4.0)
outlook = rainy
|windy = TRUE: no (2.0)
|windy = FALSE: yes (3.0)
Number of Leaves : 5
Size of the tree :
8
Time taken to build model: 0.02 seconds
=== Stratified cross-validation ===
=== Summary ===
Correctly Classified Instances
Incorrectly Classified Instances
Kappa statistic
Mean absolute error
Root mean squared error
Relative absolute error
Root relative squared error
Total Number of Instances

9
5

64.2857 %
35.7143 %
0.186
0.2857
0.4818
60
%
97.6586 %
14

=== Detailed Accuracy By Class ===


TP Rate FP Rate Precision Recall F-Measure ROC Area Class
0.778 0.6
0.7
0.778 0.737
0.789 yes
0.4
0.222 0.5
0.4
0.444
0.789 no
=== Confusion Matrix ===
a b <-- classified as
7 2 | a = yes
3 2 | b = no

CHALAPATHI INSTITUTE OF TECHNOLOGY

Tree View:

Visualize Classify Errors :

CHALAPATHI INSTITUTE OF TECHNOLOGY

Visualize Margin curve :

Visualize Cost Curve:

10

CHALAPATHI INSTITUTE OF TECHNOLOGY

Experiment - II
Aim:
To construct a NaiveBayes Network
Description:
Suppose we have some data and we want to build a NaiveBayes from the data.
First, we need to prepare the data then fire up explorer and load in the data. Next, we select a
NaiveBayes construction method. Build a NaiveBayes Network and interpret the output.
Input:
Prepare the data as follows:
Outlook temperature humidity windy

play

overcast
Sunny
overcast
Rainy
Rainy
Rainy
overcast
Sunny
Sunny
Rainy
Sunny
overcast
overcast
Rainy

no
no
yes
yes
yes
no
yes
no
yes
yes
yes
yes
yes
no

85
80
83
70
68
65
64
72
69
75
75
72
81
71

85
90
86
96
80
70
65
95
70
80
80
90
75
91

FALSE
TRUE
FALSE
FALSE
FALSE
TRUE
TRUE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
TRUE

Save this book.csv and open csv (cmd delimited).Load the data into Explorer

11

CHALAPATHI INSTITUTE OF TECHNOLOGY

Lets load the data into Explorer and start analyzing. Pick up WEKA to get the panel shown below.
Click on Applications Menu.

Select Explorer option. The Explorer screen will be shown below:


12

CHALAPATHI INSTITUTE OF TECHNOLOGY

In the Explorer screen 6 tabs along with the top are the basic operations that the explorer supports.
Right now, we are on the Preprocess tab.
First, select the classify tab in the explorer. Then choose button at the top left of the opening
tree section of the hierarchical menu shown below. The menu structure represents the organization of
WEKA code into modules.
Click on Open file, Select appropriate data file. The Explorer having the loaded file, the
screen will be as shown below.
Suppose the open file is weather.arff.

13

CHALAPATHI INSTITUTE OF TECHNOLOGY

This tells you about the datasets. It has 14 instances and 5 attributes.
The attributes are :
Outlook
Temperature
Humidity
Windy
Play
The first attribute outlook is selected by default. It has no missing values.
The actual values are sunny, overcast, rainy and they occur 5, 4, 5 times respectively.
A histogram at the lower right shows how often each of the 2 values of the class outlook which is
as shown in above figure.
NaiveBayes appears in the line beside the choose button as shown in the figure below:

14

CHALAPATHI INSTITUTE OF TECHNOLOGY

If you click the line GUI, generic object editor is displayed. Having classify as the button. Click
on the start button.
Examining the output:
The figure below shows the output. At the beginning is a summary of the dataset and the
fact that 10-fold cross-validation is used to evaluate it. Then comes a pruned decision-tree in textual
form. The first split is on the outlook attribute and then second level. The splits are on humidity, windy
respectively. In the tree structure a colon introduced a class that has been assigned, designed a particular
leaf followed by the number of instances that reach the leaf.

15

CHALAPATHI INSTITUTE OF TECHNOLOGY

Classifier Output :
=== Run information ===
Scheme:
weka.classifiers.bayes.NaiveBayes
Relation: weather
Instances: 14
Attributes: 5
outlook
temperature
humidity
windy
play
Test mode: 10-fold cross-validation
=== Classifier model (full training set) ===

16

CHALAPATHI INSTITUTE OF TECHNOLOGY

Naive Bayes Classifier


Class yes: Prior probability = 0.63
outlook: Discrete Estimator. Counts = 3 5 4 (Total = 12)
temperature: Normal Distribution. Mean = 72.9697 StandardDev = 5.2304 WeightSum = 9 Precision =
1.9090909090909092
humidity: Normal Distribution. Mean = 78.8395 StandardDev = 9.8023 WeightSum = 9 Precision =
3.4444444444444446
windy: Discrete Estimator. Counts = 4 7 (Total = 11)
Class no: Prior probability = 0.38
outlook: Discrete Estimator. Counts = 4 1 3 (Total = 8)
temperature: Normal Distribution. Mean = 74.8364 StandardDev = 7.384 WeightSum = 5 Precision =
1.9090909090909092
humidity: Normal Distribution. Mean = 86.1111 StandardDev = 9.2424 WeightSum = 5 Precision =
3.4444444444444446
windy: Discrete Estimator. Counts = 4 3 (Total = 7)
Time taken to build model: 0 seconds
=== Stratified cross-validation ===
=== Summary ===
Correctly Classified Instances
9
64.2857 %
Incorrectly Classified Instances
5
35.7143 %
Kappa statistic
0.1026
Mean absolute error
0.4649
Root mean squared error
0.543
Relative absolute error
97.6254 %
Root relative squared error
110.051 %
Total Number of Instances
14
=== Detailed Accuracy By Class ===
TP Rate FP Rate Precision Recall F-Measure ROC Area Class
0.889 0.8
0.667 0.889 0.762
0.444 yes
0.2
0.111 0.5
0.2
0.286
0.444 no

17

CHALAPATHI INSTITUTE OF TECHNOLOGY


=== Confusion Matrix ===
a b <-- classified as
8 1 | a = yes
4 1 | b = no
Visualize Margin Curve :

18

CHALAPATHI INSTITUTE OF TECHNOLOGY


Visualize Threshold Curve :

Visualize Cost Curve :

19

CHALAPATHI INSTITUTE OF TECHNOLOGY

Experiment III
Aim:
To construct a Bayes Network
Description:
Suppose we have some data and we want to build a Bayes Network from the data.
First, we need to prepare the data then fire up explorer and load in the data. Next, we select a Bayes
Network construction method. Build a Bayes Network and interpret the output.
Input:
Prepare the data as follows:
outlook

temperature humidity windy

play

overcast
sunny
overcast
rainy
rainy
rainy
overcast
sunny
sunny
rainy
sunny
overcast
overcast
rainy

85
80
83
70
68
65
64
72
69
75
75
72
81
71

no
no
yes
yes
yes
no
yes
no
yes
yes
yes
yes
yes
no

85
90
86
96
80
70
65
95
70
80
80
90
75
91

FALSE
TRUE
FALSE
FALSE
FALSE
TRUE
TRUE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
TRUE

Save this book.csv and open csv (cmd delimited).Load the data into Explorer

20

CHALAPATHI INSTITUTE OF TECHNOLOGY

Lets load the data into Explorer and start analyzing. Pick up WEKA to get the panel shown below.
Click on Applications Menu.

Select Explorer option. The Explorer screen will be shown below:


21

CHALAPATHI INSTITUTE OF TECHNOLOGY

In the Explorer screen 6 tabs along with the top are the basic operations that the explorer supports.
Right now, we are on the Preprocess tab.
First, select the classify tab in the explorer. Then choose button at the top left of the opening
tree section of the hierarchical menu shown below. The menu structure represents the organization of
WEKA code into modules.
Click on Open file, Select appropriate data file. The Explorer having the loaded file, the
screen will be as shown below.

22

CHALAPATHI INSTITUTE OF TECHNOLOGY

Suppose the open file is weather.arff.

This tells you about the datasets. It has 14 instances and 5 attributes.

23

CHALAPATHI INSTITUTE OF TECHNOLOGY


The attributes are :
Outlook
Temperature
Humidity
Windy
Play
The first attribute outlook is selected by default. It has no missing values.
The actual values are sunny, overcast, rainy and they occur 5, 4, 5 times respectively.
A histogram at the lower right shows how often each of the 2 values of the class outlook which is
as shown in above figure.
BayesNetwork appears in the line beside the choose button as shown in the figure below:

If you click the line GUI, generic object editor is displayed. Having classify as the button. Click
on the start button.

24

CHALAPATHI INSTITUTE OF TECHNOLOGY

Examining the output:


The figure below shows the output. At the beginning is a summary of the dataset and the
fact that 10-fold cross-validation is used to evaluate it. Then comes a pruned decision-tree in textual
form. The first split is on the outlook attribute and then second level. The splits are on humidity, windy
respectively. In the tree structure a colon introduced a class that has been assigned, designed a particular
leaf followed by the number of instances that reach the leaf.

Classifier Output :
=== Run information ===
Scheme:
weka.classifiers.bayes.BayesNet -D -Q weka.classifiers.bayes.net.search.local.K2 -- -P 1
-S BAYES -E weka.classifiers.bayes.net.estimate.SimpleEstimator -- -A 0.5
Relation: weather
Instances: 14
Attributes: 5
outlook
temperature
humidity
windy
play
25

CHALAPATHI INSTITUTE OF TECHNOLOGY


Test mode: 10-fold cross-validation
=== Classifier model (full training set) ===
Bayes Network Classifier
not using ADTree
#attributes=5 #classindex=4
Network structure (nodes followed by parents)
outlook(3): play
temperature(1): play
humidity(1): play
windy(2): play
play(2):
LogScore Bayes: -39.49991749238267
LogScore BDeu: -46.697734525428125
LogScore MDL: -46.72727827843424
LogScore ENTROPY: -37.49057762478084
LogScore AIC: -44.49057762478084
Time taken to build model: 0 seconds
=== Stratified cross-validation ===
=== Summary ===
Correctly Classified Instances
8
57.1429 %
Incorrectly Classified Instances
6
42.8571 %
Kappa statistic
-0.0244
Mean absolute error
0.4671
Root mean squared error
0.5221
Relative absolute error
98.0951 %
Root relative squared error
105.8276 %
Total Number of Instances
14
=== Detailed Accuracy By Class ===
TP Rate FP Rate Precision Recall F-Measure ROC Area Class
0.778 0.8
0.636 0.778 0.7
0.511 yes
0.2
0.222 0.333 0.2
0.25
0.511 no
=== Confusion Matrix ===
a b <-- classified as
7 2 | a = yes
4 1 | b = no

26

CHALAPATHI INSTITUTE OF TECHNOLOGY

Visualize Classify Errors:

Visualize Graph :

27

CHALAPATHI INSTITUTE OF TECHNOLOGY


Visualize Margin Curve :

Visualize Threshold Curve :

28

CHALAPATHI INSTITUTE OF TECHNOLOGY

Visualize Cost Curve :

29

CHALAPATHI INSTITUTE OF TECHNOLOGY

Experiment IV
Aim:
To perform classification
Description:It is necessary to provide a clear classification of data mining systems which may help
users to distinguish between such systems and to identify them.
Data mining classification can be done in different ways:
1) Data mining can be classified according to the kinds of databases mined
2) Data mining can be Classified according to the kinds of knowledge mined which is done
based on the mining functionalities like characterization, discrimination etc
3) We can also classify the data mining systems according to the kinds of techniques utilized,
applications adapted.
Input:
customer ID
1
2
3
4
5
6
7
8
9
10
11
12
13
14

age
youth
youth
middle
senior
senior
senior
middle
youth
youth
senior
youth
middle
middle
senior

income
high
high
high
medium
low
low
low
medium
low
medium
medium
medium
high
Medium

student
no
no
no
no
yes
yes
yes
no
yes
yes
yes
no
yes
no

credit rating
fair
excellent
fair
fair
fair
excellent
excellent
fair
fair
fair
excellent
excellent
fair
excellent

class By computer
no
no
yes
yes
yes
no
yes
no
yes
yes
yes
yes
yes
no

\
FIGURE 1: INPUT FILE (CLASSIFY.CSV)

30

CHALAPATHI INSTITUTE OF TECHNOLOGY


Artificial Neural Network Model:It is usually called as Neural Network which is a mathematical or a computational model.
Multilayer Perceptron:
It is a feed forward artificial neural network model that maps set of input data on to a set of
appropriate output.
It consists of multiple layers of nodes in a directed graph with each layer fully connected to
next one.
Except for the input nodes, each node is a neuron also called as processing element with
a nonlinear activation function.
It is a modification of the standard linear Perceptron which can distinguish data i.e. not linearly
separable.
Now Open the WEKA GUI Chooser from start menuall programs and click on the
EXPLORER button.
Now click on the Open File button and choose the file named as classify.csv where the
content of classify.csv is as shown in the figure 1.

FIGURE 2: LOAD THE FILE CLASSIFY.CSV

After loading the input file named classify.csv as shown in figure 2, choose the classify tab in the
WEKA explorer window.
Under the classify tab click on choose button and select the Multilayer Perceptron under
functions as shown in the following figure 3.

31

CHALAPATHI INSTITUTE OF TECHNOLOGY

FIGURE 3: SELECTING MULTILAYER PERCEPTRON

Now select the use training set under the Test Options located at the left of the WEKA
explorer window and click on start button.
The output is represented in the Classifier Output window in weka explorer window, which is
as shown in figure 4 below:

FIGURE 4: SHOWING OUTPUT IN CLASSIFIER OUTPUT WINDOW IN WEKA EXPLORER WINDOW

32

CHALAPATHI INSTITUTE OF TECHNOLOGY


We can also view the output in a separate window by right clicking on the option in Result list
and clicking on view in separate window as shown in figure 5.

FIGURE 5: SELECTING THE OPTION "VIEW IN SEPARATE WINDOW"

The output is viewed in a separate window is as follows:


=== Run information ===
Scheme:weka.classifiers.functions.MultilayerPerceptron -L 0.3 -M 0.2 -N 500 -V 0 -S 0 -E 20 -H a
Relation: classify
Instances:14
Attributes:6 customer ID age
income
student credit rating
class By computer
Test mode:evaluate on rainingdata
=== Classifier model (full training set) === Sigmoid Node 0
Inputs Weights
Threshold 4.597303099925899
Node 2
-2.965811084944313
Node 3
-2.8207211391081324
Node 4
-2.5343621922785937
Node 5
-0.7092926749950742
Node 6
-3.202080364079574
Sigmoid Node 1
Inputs Weights
Threshold -4.590882027556084
Node 2 2.936363944100418
Node 3 2.8380779417219175
Node 4 2.5358725504279915
33

CHALAPATHI INSTITUTE OF TECHNOLOGY


Node 5 0.6559016508925626
Node 6 3.230555090955558
Sigmoid Node 2
Inputs Weights
Threshold -0.08047245781235832
Attrib customer ID 0.22193220508213732
Attrib age=youth -1.5127951967716864
Attrib age=middle 1.8498200753538858
Attrib age=senior -0.3411353536325934
Attrib income=high -0.3203721986959815
Attrib income=medium 1.3074938148771482
Attrib income=low
-0.9766407864775274
Attrib student 3.3163099912451774
Attrib credit rating -2.239705348709711
Sigmoid Node 3
Inputs Weights
Threshold -0.08606520678501425
Attrib customer ID 0.22787351339623643
Attrib age=youth -1.4568491246182191
Attrib age=middle 1.8065079530931696
Attrib age=senior -0.32844652534937113
Attrib income=high -0.3044507586834089
Attrib income=medium 1.2822518641711322
Attrib income=low
-0.9331363251717437
Attrib student 3.210625483183134
Attrib credit rating -2.1592561505892798
Sigmoid Node 4
Inputs Weights
Threshold -0.10045745915917204
Attrib customer ID 0.2609258565067224
Attrib age=youth -1.3491882905571375
Attrib age=middle 1.7163298243001262
Attrib age=senior -0.29465813645261985
Attrib income=high -0.2787472175956876
Attrib income=medium 1.1737333812906028
Attrib income=low
-0.8138256247222926
Attrib student 2.9167768340074973
Attrib credit rating -2.0180847298886704
Sigmoid Node 5
Inputs Weights
Threshold -0.4062972229764489
Attrib customer ID 0.23329558490703314
Attrib age=youth -0.24798044277287876
Attrib age=middle 1.1121334434039274
Attrib age=senior -0.3946052232908662
Attrib income=high 0.06310320479245372
34

CHALAPATHI INSTITUTE OF TECHNOLOGY


Attrib income=medium 0.3546927981498891
Attrib income=low
-0.010888839973622326
Attrib student 1.2539279626118915
Attrib credit rating -0.6857273386061201
Sigmoid Node 6
Inputs Weights
Threshold 2.693721030885051E-4
Attrib customer ID 0.2975412089953832
Attrib age=youth -1.586507555483025
Attrib age=middle 1.9784283043459296
Attrib age=senior -0.31868335584842467
Attrib income=high -0.32524337164708084
Attrib income=medium 1.368485717420782
Attrib income=low
-1.0617305103863552
Attrib student 3.5359771210150868
Attrib credit rating -2.3960911468747335
Class no Input Node 0
Class yes
Input
Node 1
Time taken to build model: 0.19seconds
=== Evaluation on training set ===
=== Summary ===
Correctly Classified Instances

14
0

100
%

% Incorrectly Classified Instances

Kappa statistic
1
Mean absolute error
0.0242
Root mean squared error
0.0349
Relative absolute error
5.2211 %
Root relative squared
7.2691
error
%
Total Number of
14
Instances
=== Detailed Accuracy By Class ===
TP Rate FP Rate Precision Recall F-Measure ROC Area Class
1
0 1
1
1
1
no
1
0 1
1
1
1
yes
Weighted
1 0
1
1
1
1
Avg.
=== Confusion Matrix ===
a b <-- classified as
5 0 | a = no
0 9 | b = yes
35

CHALAPATHI INSTITUTE OF TECHNOLOGY

Experiment V
Aim:
To perform clustering
Description:
Cl ustering is a task of assigning a set of objects into groups called as clusters.
Clustering is also referred as cluster analysis where the objects in the same cluster are more similar
to each other than to those objects in other clusters.
Clustering is the main task of Explorative Data mining and is a common technique for statistical data
analysis used in many fields like machine learning, pattern recognition, image analysis, bio informatics
etc
Cluster analysis is not an algorithm but is a general task to be solved.
Clustering is of different types like hierarchical clustering which creates a hierarchy of
clusters, partial clustering, and spectral clustering.
Input:
customer ID
1
2
3
4
5
6
7
8
9
10
11
12
13
14

age
youth
youth
middle
senior
senior
senior
middle
youth
youth
senior
youth
middle
middle
senior

income
high
high
high
medium
low
low
low
medium
low
medium
medium
medium
high
Medium

student
no
no
no
no
yes
yes
yes
no
yes
yes
yes
no
yes
no

credit rating
fair
excellent
fair
fair
fair
excellent
excellent
fair
fair
fair
excellent
excellent
fair
excellent

class By computer
no
no
yes
yes
yes
no
yes
no
yes
yes
yes
yes
yes
No

FIGURE 1: INPUT FILE (CLUSTER.CSV)

36

CHALAPATHI INSTITUTE OF TECHNOLOGY


Simple K-Means: It is a method of cluster analysis called as partial cluster analysis or partial clustering. K-Means
clustering partition or divides n observations into K clusters.
Each observation belongs to the cluster with the nearest mean.
K-means clustering is an algorithm to group the objects based on attributes/features into K
number of groups where K is positive integer.
K-Means clustering is used in different types of applications like pattern recognition,
artificial intelligent, image processing, etc
Now Open the WEKA GUI Chooser from start menuall programs and click on the
EXPLORER button.
Now click on the Open File button and choose the file named as cluster.csv where the
content of cluster.csv is as shown in the figure 1.

FIGURE 2: LOAD THE FILE CLUSTER.CSV

After loading the input file named cluster.csv as shown in figure 2, choose the cluster tab in the
WEKA explorer window.
Under the cluster tab click on choose button and select the SimpleKMeans under clusterers
as shown in the following figure 3.

37

CHALAPATHI INSTITUTE OF TECHNOLOGY

FIGURE 3: SELECTING SIMPLEKMEANS

Now select the use training set under the Test Options located at the left of the WEKA
explorer window and click on start button.
The output is represented in the Clusterer Output window in weka explorer window, which is
as shown in figure 4 below:

FIGURE 4: SHOWING OUTPUT IN CLUSTERER OUTPUT WINDOW IN WEKA EXPLORER WINDOW

38

CHALAPATHI INSTITUTE OF TECHNOLOGY


We can also view the output in a separate window by right clicking on the option in Result list
and clicking on view in separate window as shown in figure 5.

FIGURE 5: SELECTING THE OPTION "VIEW IN SEPARATE WINDOW"

The output is viewed in a separate window is as follows:


=== Run information ===
Scheme:weka.clusterers.SimpleKMeans -N 2 -A "weka.core.EuclideanDistance -R first-last" -I 500 -S
10
Relation: weka exp-4
Instances:14
Attributes:6 customer ID age
income
student credit rating
class By computer
Test mode:evaluate on training data
=== Model and evaluation on training set ===
kMeans
======
Number of iterations: 3
Within cluster sum of squared errors: 27.25105663567202
Missing values globally replaced with mean/mode
Cluster centroids:
39

CHALAPATHI INSTITUTE OF TECHNOLOGY

Cluster#
Attribute
Full Data
0
1
(14)
(7)
(7)
=================================================
customer ID
7.5
8.5714 6.428
youth
youth
6
age income
mediu
mediu middle
student
m no
m yes high
credit
fair
fair
rating
no
class By computer
yes
yes
Clustered Instances
0
1

7 ( 50%)
7 ( 50%)

40

CHALAPATHI INSTITUTE OF TECHNOLOGY

Experiment VI
Aim:
To perform Association Rule.
It is a popular method for discovering interesting relations between variables in
large databases.
It is used to identify the most frequent item sets or frequent patterns that occur frequently in a
database.
To perform association rule mining we need two parameters like:
Support: - It is the total probability of the item sets that occurred in the transaction.
Confidence: - it is the ratio of probability of two item sets A,B and the probability of the item set A.
Association rule mining is used in different applications like basket analysis, catalog
design, clustering, classification etc
Input:
Trans ID
t1
t2
t3
t4
t5
t6
t7
t8
t9

Item list
i1,i2,i5
i2,i4
i2,i3
i1,i2,i4
i1,i3
i2,i3
i1,i3
i1,i2,i3,i5
i1,i2,i3

FIGURE 1: INPUT FILE (ASSOCIATION.CSV)

41

CHALAPATHI INSTITUTE OF TECHNOLOGY

Apriori Algorithm:To implement the association rule we use this algorithm.


Steps to follow while implementing the association rule are:
1. Find the frequent item sets where the items have the minimum support count.
2. Use the frequent item sets to generate association rules.
3. Generate the candidates by performing join operation.
4. Perform pruning operation i.e. if any one of the candidates that have a subset is not frequent in
the set then delete it.
5. Also calculate support count for each candidate and delete those candidates whose
minimum support count is not satisfied.
Now Open the WEKA GUI Chooser from start menuall programs and click on the
EXPLORER button.
Now click on the Open File button and choose the file named as association.csv where the
content of association.csv is as shown in the figure 1

FIGURE 2: LOAD THE FILE ASSOCIATION.CSV

After loading the input file named association.csv as shown in figure 2, choose the associate
tab in the WEKA explorer window.
Under the associate tab click on choose button and select the Apriori Algorithm under
associations as shown in the following figure 3.

42

CHALAPATHI INSTITUTE OF TECHNOLOGY

FIGURE 3: SELECTING APRIORI ALGORITHM

Now click on start button.


After clicking on start button, the output is represented in the Associator Output window
in weka explorer window, which is as shown in figure 4 below:

FIGURE 4: SHOWING OUTPUT IN ASSOCIATOR OUTPUT WINDOW IN WEKA EXPLORER WINDOW

We can also view the output in a separate window by right clicking on the option in Result list
and clicking on view in separate window as shown in figure 5.
43

CHALAPATHI INSTITUTE OF TECHNOLOGY

FIGURE 5: SELECTING THE OPTION "VIEW IN SEPARATE WINDOW"

The output is viewed in a separate window is as follows:


=== Run information ===
Scheme:
weka.associations.Apriori -N 10 -T 0 -C 0.9 -D 0.05 -U 1.0 -M 0.1 -S -1.0 -c -1
Relation:
weka exp-3
Instances: 9
Attributes: 2
Trans ID Item list
=== Associator model (full training set) ===
Apriori
=======
Minimum support: 0.16 (1 instances) Minimum metric <confidence>: 0.9
Number of cycles performed: 17
Generated sets of large itemsets: Size of set of large itemsets L(1): 16
Size of set of large itemsets L(2): 9
Best rules found:
1. Item list=i1,i2,i5 1 ==> Trans ID=t1 1 conf:(1)
2. Trans ID=t1 1 ==> Item list=i1,i2,i5 1 conf:(1)
3. Item list=i2,i4 1 ==> Trans ID=t2 1 conf:(1)
4. Trans ID=t2 1 ==> Item list=i2,i4 1 conf:(1)
5. Trans ID=t3 1 ==> Item list=i2,i3 1 conf:(1)
6. Item list=i1,i2,i4 1 ==> Trans ID=t4 1 conf:(1)
7. Trans ID=t4 1 ==> Item list=i1,i2,i4 1 conf:(1)
8. Trans ID=t5 1 ==> Item list=i1,i3 1 conf:(1)
9. Trans ID=t6 1 ==> Item list=i2,i3 1 conf:(1)
10. Trans ID=t7 1 ==> Item list=i1,i3 1 conf:(1)
44

CHALAPATHI INSTITUTE OF TECHNOLOGY

AIM:
Write a program in java, which performs a digital signature on a given text.
PROGRAM:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import sun.misc.BASE64Encoder;
public class DigSign {
public static void main(String[] args) throws Exception {
// TODO code application logic here
KeyPairGeneratorkpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPairkeyPair = kpg.genKeyPair();
byte[] data = "Sample Text".getBytes("UTF8");
Signature sig = Signature.getInstance("MD5WithRSA");
sig.initSign(keyPair.getPrivate());
sig.update(data);
byte[] signatureBytes = sig.sign();
System.out.println("Signature: \n" + new BASE64Encoder().encode(signatureBytes));

sig.initVerify(keyPair.getPublic());
sig.update(data);
System.out.println(sig.verify(signatureBytes));
}
}
OUTPUT:
Signature:
imwaKe99tkM6H6hiiP0rubmb/MrYJZLi
wLdRSjslF2KlA5B23az5M2LKftQFCB+NH
Ce5F5/YfN8OsNSNLtucrrZTah0SrdWSzdGCOfYLdUZmPQ72j1SkLhYspsTsUb/U

45

CHALAPATHI INSTITUTE OF TECHNOLOGY

AIM:
Write a Java program to implement RSA Algoithm.
PROGRAM:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.Random;
import java.util.Scanner;
public class RSA {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO code application logic here
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger(); // Here's one prime number..
System.out.print("Enter an
other prime number: ");
BigInteger q = sc.nextBigInteger(); // ..and another.
BigInteger n = p.multiply(q);
BigInteger n2 = p.subtract(BigInteger.ON
E).multiply(q.subtract(BigInteger.ONE));
BigInteger e = generateE(n2);
BigInteger d = e.modInverse(n2); // Here's the multiplicative inverse
System.out.println("Encryption keys are: " + e + ", " + n);
System.out.println("Decryption keys are: " + d + ", " + n);
}
public static BigIntegergenerateE(BigIntegerfiofn) {
int y, intGCD;
BigInteger e;
BigInteger gcd;
Random x = new Random();
do {
y = x.nextInt(fiofn.intValue()-1);
String z = Integer.toString(y);
e = new BigInteger(z);
gcd = fiofn.gcd(e);
intGCD = gcd.intValue();
46

CHALAPATHI INSTITUTE OF TECHNOLOGY

}
while(y <= 2 || intGCD != 1);
return e;
}
}

OUTPUT:
Enter a Prime number: 5
Enter another prime number: 11
Encryption keys are: 33, 55
Decryption keys are: 17, 55

47

CHALAPATHI INSTITUTE OF TECHNOLOGY

AIM:
Write a Java program to implement the DES algorithm logic.
PROGRAM:
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.s
pec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DES {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
privateKeySpecmyKeySpec;
privateSecretKeyFactorymySecretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public DES() throws Exception {
// TODO code application logic here
myEncryptionKey = "ThisIsSecretEncryptionKey";
myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
myKeySpec = new DESedeKeySpec(keyAsBytes);
mySecretKeyFactory = SecretKeyFacto
ry.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = mySecretKeyFactory.generateSecret(myKeySpec);
}
48

CHALAPATHI INSTITUTE OF TECHNOLOGY

public String encrypt(String unencryptedString) {


String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
BASE64Encoder base64encoder = new BASE64Encoder();
encryptedString = base64encoder.encode(encryptedText); }
catch (Exception e) {
e.printStackTrace(); }
returnencryptedString; }
public String decrypt(St
ring encryptedString) {
String decryptedText=null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
BASE64Decoder base64decoder = new BASE64Decoder();
byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
byte[] plainText = cipher
.doFinal(encryptedText);
decryptedText= bytes2String(plainText); }
catch (Exception e) {
e.printStackTrace(); }
returndecryptedText; }
private static String byte
s2String(byte[] bytes) {
StringBufferstringBuffer = new StringBuffer();
for (int i = 0; i <bytes.length; i++) {
stringBuffer.append((char) bytes[i]); }
returnstringBuffer.toString(); }
public static void main(String args []) throws Exception {
System.out.print("En
ter the string: ");
DES myEncryptor= new DES();
String stringToEncrypt = br.readLine();
String encrypted = myEncryptor.encrypt(stringToEncrypt);
String decrypted = myEncryptor.decrypt(encrypted);
System.out.println("\nString To Encrypt: " +stringToEncrypt);
System.out.println("\nEncrypted Value : " +encrypted);
System.out.println
49

CHALAPATHI INSTITUTE OF TECHNOLOGY

("\nDecrypted Value : " +decrypted);


System.out.println("");
}
}

OUTPUT:
Enter the string: Welcome
String To Encrypt: Welcome
Encrypted Value : BPQMwc0wKvg=
Decrypted Value : Welcome

50

CHALAPATHI INSTITUTE OF TECHNOLOGY

AIM:
Write a Java program to perform encryption and decryption using the
following algorithms:
a)Ceaser Cipher
b)Substitution Cipher
c)Hill Cipher
PROGRAM:
a)Ceaser Cipher
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CeaserCipher {
static Scanner sc=new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// TODO code application logic here
System.out.print("En
ter any String: ");
String str = br.readLine();
System.out.print("\nEnter the Key: ");
int key = sc.nextInt();
String encrypted = encrypt(str, key);
System.out.println("\nEncrypted String is: " +encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("\nDecrypted String is: " +decrypted);
System.out.println("\n");
}
public static String encrypt(String str, int key) {
String encrypted = "";
for(int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if (Character.isUpperCase(c)) {
c = c + (key % 26);
if (c > 'Z')
c = c - 26;
51

CHALAPATHI INSTITUTE OF TECHNOLOGY

}
else if (Character.isLowerCase(c)) {
c = c + (key % 26);
if (c > 'z')
c = c - 26;
}
encrypted += (char) c;
}
return encrypted;
}
public static String decrypt(String str, int key) {
String decrypted = "";
for(int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if (Character.isUpperCase(c)) {
c = c - (key % 26);
if (c < 'A')
c = c + 26;
}
else if (Character.isLowerCase(c)) {
c = c - (key % 26);
if (c < 'a')
c = c + 26;
}
decrypted += (char) c;
}
return decrypted;
}
}
Output:
Enter any String: Hello World
Enter the Key: 5
Encrypted String is: MjqqtBtwqi
Decrypted String is: Hello World

52

CHALAPATHI INSTITUTE OF TECHNOLOGY

b)Substitution Cipher
PROGRAM:
import java.io.*;
import java.util.*;
public class SubstitutionCipher {
static Scanner sc = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// TODO code application logic here
String a = "abcdefghijklmnopqrstuvwxyz";
String b = "zyxwvutsrqponmlkjihgfedcba";
System.out.print("En
ter any string: ");
String str = br.readLine();
String decrypt = "";
char c;
for(int i=0;i<str.length();i++)
{
c = str.charAt(i);
int j = a.indexOf(c);
decrypt = decrypt+b.charAt(j);
}
System.out.println("The encr
ypted data is: " +decrypt);
}
}

Output:
Enter any string: aceho
The encrypted data is: zxvsl

53

CHALAPATHI INSTITUTE OF TECHNOLOGY

C) Hill Cipher
PROGRAM:
import java.io.*;
import java.util.*;
import java.io.*;
public class HillCipher {
static float[][] decrypt = new float[3][1];
static float[][] a = new float[3][3];
static float[][] b = new float[3][3];
static float[][] mes = new float[3][1];
static float[][] res = new float[3][1];
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// TODO code application logic here
getkeymes();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
res[i][j]=res[i][j]+a[i][k]*mes[k][j]; }
System.out.print("\nEncrypted string is : ");
for(int i=0;i<3;i++) {
System.out.print((char)(res[i][0]%26+97));
res[i][0]=res[i][0];
}
inverse();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
decrypt[i][j] = decrypt[i][j]+b[i][k]*res[k][j]; }
System.out.print("\nDecr
ypted string is : ");
for(int i=0;i<3;i++){
System.out.print((char)(decrypt[i][0]%26+97));
}
System.out.print("\n");
}
54

CHALAPATHI INSTITUTE OF TECHNOLOGY

public static void getkey


mes() throws IOException {
System.out.println("Enter 3x3 matrix for key (It should be inversible): ");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j] = sc.nextFloat();
System.out.print("
\nEnter a 3 letter string: ");
String msg = br.readLine();
for(int i=0;i<3;i++)
mes[i][0] = msg.charAt(i)-97;
}
public static void inverse() {
floatp,q;
float[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
//a[i][j]=sc.nextFloat();
if(i==j)
b[i][j]=1;
else b[i][j]=0;
}
for(int k=0;k<3;k++) {
for(int i=0;i<3;i++) {
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++) {
if(i!=k) {
c[i][j] = c[i][j]*q-p*c[k][j];
b[i][j] = b[i][j]*q-p*b[k][j];
}}}}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
b[i][j] = b[i][j]/c[i][i]; }
System.out.println("");
System.out.println("\nInverse Matrix is : ");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++)
System.out.print(b[i][j] + " ");
System.out.print("\n"); }
55

CHALAPATHI INSTITUTE OF TECHNOLOGY

}}

Output:
Enter a 3 letter string: hai
Encrypted string is :fdx
Inverse Matrix is :
0.083333336 0.41666666 -0.33333334
-0.41666666 -0.083333336 0.6666667
0.5833333 -0.083333336 -0.33333334
Decrypted string is :hai

56

CHALAPATHI INSTITUTE OF TECHNOLOGY

Ex No 1: PROGRAM USING SIMPLE UDP


DOMAIN NAME SYSTEM

AIM:
To write a C program to develop a DNS client server to resolve the given
hostname.
Program :
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main(int argc,char *argv[1])
{
struct hostent *hen;
if(argc!=2)
{
fprintf(stderr,"Enter the hostname \n");
exit(1);
}
hen=gethostbyname(argv[1]);
if(hen==NULL)
{
fprintf(stderr,"Host not found \n");
}
printf("Hostname is %s \n",hen->h_name);
printf("IP address is %s \n",inet_ntoa(*((struct in_addr *)hen->h_addr)));
}
RESULT:
Thus the above program udp performance using domain name server was
executed and successfully
EX NO 2 :
PROGRAMS USING RAW SOCKETS (LIKE PACKET CAPTURING AND
FILTERING)

57

CHALAPATHI INSTITUTE OF TECHNOLOGY

AIM :
To implement programs using raw sockets (like packet capturing and filtering)
//---cat rawtcp.c--// Run as root or SUID 0, just datagram no data/payload
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
// Packet length
#define PCKT_LEN 8192
// May create separate header file (.h) for all
// headers' structures
// IP header's structure
struct ipheader {
unsigned char iph_ihl:5, /* Little-endian */
iph_ver:4;
unsigned char iph_tos;
unsigned short int iph_len;
unsigned short int iph_ident;
unsigned char iph_flags;
unsigned short int iph_offset;
unsigned char iph_ttl;
unsigned char iph_protocol;
unsigned short int iph_chksum;
unsigned int iph_sourceip;
unsigned int iph_destip;
};
/* Structure of a TCP header */
struct tcpheader {
unsigned short int tcph_srcport;
unsigned short int tcph_destport;
unsigned int tcph_seqnum;
unsigned int tcph_acknum;
unsigned char tcph_reserved:4, tcph_offset:4;
// unsigned char tcph_flags;
unsigned int
tcp_res1:4, /*little-endian*/
tcph_hlen:4, /*length of tcp header in 32-bit
words*/
tcph_fin:1, /*Finish flag "fin"*/
tcph_syn:1, /*Synchronize sequence numbers to
start a connection*/
tcph_rst:1, /*Reset flag */
58

CHALAPATHI INSTITUTE OF TECHNOLOGY


tcph_psh:1, /*Push, sends data to the
application*/
tcph_ack:1, /*acknowledge*/
tcph_urg:1, /*urgent pointer*/
tcph_res2:2;
unsigned short int tcph_win;
unsigned short int tcph_chksum;
unsigned short int tcph_urgptr;
};
// Simple checksum function, may use others such as Cyclic
Redundancy Check, CRC
unsigned short csum(unsigned short *buf, int len)
{
unsigned long sum;
for(sum=0; len>0; len--)
sum += *buf++;
sum = (sum >> 16) + (sum &0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
int main(int argc, char *argv[])
{
int sd;
// No data, just datagram
char buffer[PCKT_LEN];
// The size of the headers
struct ipheader *ip = (struct ipheader *) buffer;
struct tcpheader *tcp = (struct tcpheader *) (buffer +
sizeof(struct ipheader));
struct sockaddr_in sin, din;
int one = 1;
const int *val = &one;
memset(buffer, 0, PCKT_LEN);
if(argc != 5)
{
printf("- Invalid parameters!!!\n");
printf("- Usage: %s <source hostname/IP> <source port>
<target hostname/IP> <target port>\n", argv[0]);
exit(-1);
}
sd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);
if(sd < 0)
{
perror("socket() error");
exit(-1);
}
59

CHALAPATHI INSTITUTE OF TECHNOLOGY


else
printf("socket()-SOCK_RAW and tcp protocol is OK.\n");
// The source is redundant, may be used later if needed
// Address family
sin.sin_family = AF_INET;
din.sin_family = AF_INET;
// Source port, can be any, modify as needed
sin.sin_port = htons(atoi(argv[2]));
din.sin_port = htons(atoi(argv[4]));
// Source IP, can be any, modify as needed
sin.sin_addr.s_addr = inet_addr(argv[1]);
din.sin_addr.s_addr = inet_addr(argv[3]);
// IP structure
ip->iph_ihl = 5;
ip->iph_ver = 4;
ip->iph_tos = 16;
ip->iph_len = sizeof(struct ipheader) + sizeof(struct
tcpheader);
ip->iph_ident = htons(54321);
ip->iph_offset = 0;
ip->iph_ttl = 64;
ip->iph_protocol = 6; // TCP
ip->iph_chksum = 0; // Done by kernel
// Source IP, modify as needed, spoofed, we accept through
command line argument
ip->iph_sourceip = inet_addr(argv[1]);
// Destination IP, modify as needed, but here we accept
through command line argument
ip->iph_destip = inet_addr(argv[3]);
// The TCP structure. The source port, spoofed, we accept
through the command line
tcp->tcph_srcport = htons(atoi(argv[2]));
// The destination port, we accept through command line
tcp->tcph_destport = htons(atoi(argv[4]));
tcp->tcph_seqnum = htonl(1);
tcp->tcph_acknum = 0;
tcp->tcph_offset = 5;
tcp->tcph_syn = 1;
tcp->tcph_ack = 0;
tcp->tcph_win = htons(32767);
tcp->tcph_chksum = 0; // Done by kernel
tcp->tcph_urgptr = 0;
// IP checksum calculation
ip->iph_chksum = csum((unsigned short *) buffer,
(sizeof(struct ipheader) + sizeof(struct tcpheader)));
// Inform the kernel do not fill up the headers' structure,
60

CHALAPATHI INSTITUTE OF TECHNOLOGY


we fabricated our own
if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one))
< 0)
{
perror("setsockopt() error");
exit(-1);
}
else
printf("setsockopt() is OK\n");
printf("Using:::::Source IP: %s port: %u, Target IP: %s
port: %u.\n", argv[1], atoi(argv[2]), argv[3],
atoi(argv[4]));
// sendto() loop, send every 2 second for 50 counts
unsigned int count;
for(count = 0; count < 20; count++)
{
if(sendto(sd, buffer, ip->iph_len, 0, (struct sockaddr
*)&sin, sizeof(sin)) < 0)
// Verify
{
perror("sendto() error");
exit(-1);
}
else
printf("Count #%u - sendto() is OK\n", count);
sleep(2);
}
close(sd);
return 0;
}
RESULT :
Thus the Above programs using raw sockets TCP \IP (like packet capturing and
filtering) was executed and successfully.

61

CHALAPATHI INSTITUTE OF TECHNOLOGY

EX No 3: SIMULATION OF SLIDING WINDOW PROTOCOL


AIM:
To write a C program to perform sliding window.
PROGRAM :
// SLIDING WINDOW PROTOCOL Client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mymsgbuf
{
long mtype;
char mtext[25];
};
FILE *fp;
int main()
{
struct mymsgbuf buf;
int msgid;
int i=0,s;
int count=0,frmsz;
int a[100];
char d;
if((msgid=msgget(89,IPC_CREAT|0666))==-1)
{
printf("\n ERROR IN MSGGET");
exit(0);
}
printf("\n Enter the frame size:");
scanf("%d",&frmsz);
if((fp=fopen("check","r"))==NULL)
printf("\n FILE NOT OPENED");
else
printf("\n FILE OPENED");
while(!feof(fp))
{
d=getc(fp);
a[i]=d;
i++;
62

CHALAPATHI INSTITUTE OF TECHNOLOGY


}
s=i;
for(i=0;i<frmsz;i++) //print from the check file
printf("\t %c",a[i]);
for(i=0;i<frmsz;i++)
{ if((msgrcv(msgid,&buf,sizeof(buf),0,1))==-1)
{
printf("\n ERROR IN MSGRCV");
exit(0);
}
printf("\n RECEIVED FRAMES ARE:%c",buf.mtext[i]);
}
for(i=0;i<frmsz;i++)
{ if(a[i]==buf.mtext[i])
count++;
} if(count==0)
{
printf("\n FRAMES WERE NOT RECEIVED IN CORRECT SEQ");
exit(0);
} if(count==frmsz)
{
printf("\n FRAMES WERE RECEIVED IN CORRECT SEQ");
} else
{
printf("\n FRAMES WERE NOT RECEIVED IN CORRECT SEQ");
}}
Sliding Window Protocol - Server
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mymsgbuf
{ long mtype;
char mtext[25];
};
FILE *fp;
int main()
{
struct mymsgbuf buf;
int si,ei,sz;
int msgid;
int i=0,s;
int a[100];
63

CHALAPATHI INSTITUTE OF TECHNOLOGY


char d;
if((fp=fopen("send","r"))==NULL)
printf("\n FILE NOT OPENED");
else
printf("\n FILE OPENED");
printf("\n Enter starting and ending index of frame array:");
scanf("%d%d",&si,&ei);
sz=ei-si;
if((msgid=msgget(89,IPC_CREAT|0666))==-1)
{
printf("\n ERROR IN MSGGET");
exit(0);
}
while(!feof(fp))
{
d=getc(fp);
a[i]=d;
i++;
}
s=i;
buf.mtype=1;
for(i=si;i<=ei;i++)
{
buf.mtext[i]=a[i];
}
for(i=si;i<=ei;i++) //the frames to be sent
printf("\t %c",buf.mtext[i]);
for(i=0;i<=sz;i++)
{ if((msgsnd(msgid,&buf,sizeof(buf),0))==-1)
{
printf("\n ERROR IN MSGSND");
exit(0);
}}
printf("\n FRAMES SENT");
return 0;
}
RESULT:
Thus the above program sliding window protocol was executed and successfully

64

CHALAPATHI INSTITUTE OF TECHNOLOGY

Ex No 4: ADDRESS RESOLUTION PROTOCOL


AIM:
To get the MAC or Physical address of the system using Address Resolution
Protocol.
Program:
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<net/if_arp.h>
#include<stdlib.h>
#include<stdio.h>
#include<netdb.h>
#include<sys/ioctl.h>
#include<arpa/inet.h>
int main(int argc,char *argv[])
{ int sd;
unsigned char *ptr;
struct arpreq myarp={{0}};
struct sockaddr_in sin={0};
sin.sin_family=AF_INET;
if(inet_aton(argv[1],&sin.sin_addr)==0)
{
printf("IP address Entered%s is not valid\n",argv[1]);
exit(0);
}
memcpy(&myarp.arp_pa,&sin,sizeof(myarp.arp_pa));
strcpy(myarp.arp_dev,"eth0");
sd=socket(AF_INET,SOCK_DGRAM,0);
if(ioctl(sd,SIOCGARP,&myarp)==1)
{
printf("No entry in ARP cache for%s",argv[1]);
exit(0);
}
ptr=&myarp.arp_ha.sa_data[0];
printf("MAC address for%s",argv[1]);
printf("%x%x%x%x%x%x\n",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5));
return(0);
}
65

CHALAPATHI INSTITUTE OF TECHNOLOGY


RESULT:
Thus the MAC address was generated for IP address using ARP protocol.
EX NO 5: IMPLEMENTING ROUTING PROTOCOLS
AIM:
To simulate the Implementing Routing Protocols using border gateway
protocol(BGP)

Program :

#include <stdio.h>
#include<conio.h>
int main()
{
int n;
int i,j,k;
int a[10][10],b[10][10];
printf("\n Enter the number of nodes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\n Enter the distance between the host %d - %d:",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>a[i][k]+a[k][j])
{
a[i][j]=a[i][k]+a[k][j];
}
}
}
66

CHALAPATHI INSTITUTE OF TECHNOLOGY


}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=a[i][j];
if(i==j)
{
b[i][j]=0;
}
}}
printf("\n The output matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
getch();
}
RESULT:
Thus the above program to simulate the Implementing Routing Protocols using
border gateway protocol was executed and successfully

67

CHALAPATHI INSTITUTE OF TECHNOLOGY

EX NO 6: OPEN SHORTEST PATH FIRST ROUTING PROTOCOL


AIM:
To simulate the OPEN SHORTEST PATH FIRST routing protocol based on the cost
assigned to the path.
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[5][5],n,i,j;
void main()
{
void getdata();
void shortest();
void display();
clrscr();
printf("\n\n PROGRAM TO FIND SHORTEST PATH BETWEEN TWO
NODES\n");
getdata();
shortest();
display();
getch();
}
void getdata()
{
clrscr();
printf("\n\nENTER THE NUMBER OF HOST IN THE GRAPH\n");
scanf("%d",&n);
printf("\n\nIF THERE IS NO DIRECT PATH \n");
printf(" \n\nASSIGN THE HIGHEST DISTANCE VALUE 1000 \n");
for(i=0;i<n;i++)
{
a[i][j]=0;
for(j=0;j<n;j++)
{
if(i!=j)
{
printf("\n\nENTER THE DISTANCE BETWENN (%d,
%d): ",i+1,j+1);
scanf("%d",&a[i][j]);
if(a[i][j]==0)

68

CHALAPATHI INSTITUTE OF TECHNOLOGY


a[i][j]=1000;
}
}
}
}
void shortest()
{
int i,j,k;
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(a[i][k]+a[k][j]<a[i][j])
a[i][j]=a[i][k]+a[k][j];
}
}
void display()
{
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(i!=j)
{
printf("\n SHORTEST PATH IS : (%d,%d)--%d\n",i+1,j+1,a[i][j]);
}
getch(); }
RESULT:
Thus the above program to simulate the Implementing Routing Protocols using
open shortest
path first (OSPF) was executed and successfully

69

You might also like