• No results found

Sample Program on NS2/NS3

N/A
N/A
Protected

Academic year: 2021

Share "Sample Program on NS2/NS3"

Copied!
46
0
0

Loading.... (view fulltext now)

Full text

(1)

1.

Simulate three nodes point-to-point networks with a duplex link between them. Set the

queue size and vary the bandwidth and find the number of packets dropped.

#Create simulator set ns [new Simulator]

set ntrace [open 1.tr w] $ns trace-all $ntrace set file2 [open out.nam w] $ns namtrace-all $file2 proc finish {} { global ns ntrace $ns flush-trace close $ntrace exit 0 } #create node set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] #create link $ns duplex-link $n0 $n1 10Mb 10ms DropTail $ns duplex-link $n1 $n2 10Mb 10ms DropTail

#Set Queue Size

$ns queue-limit $n0 $n1 10 $ns queue-limit $n1 $n2 10

#setup tcp connection set tcp0 [new Agent/TCP] $ns attach-agent $n0 $tcp0

#set sink to node

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

#connect tcp src and sink $ns connect $tcp0 $sink

(2)

$tcp0 set window_ 1

set cbr [new Application/Traffic/CBR] $cbr attach-agent $tcp0

$cbr set type_ CBR $cbr set packetSize_ 100 $cbr set rate_ 0.1Mb $cbr set random_ false $ns at 0.0 "$cbr start" $ns at 5.0 "finish" $ns run

---2. Apply TCP agent between n0 to n3 and UDP n1 to n3. Apply relevant applications

over TCP and UDP agents changing the parameters and determine the number of

packets sent by TCP/UDP.

set ns [new Simulator]

# Open the Trace file set ntrace [open out.tr w] $ns trace-all $ntrace # Finish procedure proc finish {} { global ns ntrace $ns flush-trace close $ntrace exit 0 }

# Create four nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node]

# Create links between the nodes

(3)

$ns duplex-link $n1 $n2 2Mb 10ms DropTail $ns simplex-link $n2 $n3 0.07Mb 20ms DropTail $ns simplex-link $n3 $n2 0.07Mb 20ms DropTail

# Set Queue Size of link (n2-n3) to 10 $ns queue-limit $n2 $n3 10

# Monitor the queue for link (n2-n3) $ns simplex-link-op $n2 $n3 queuePos 0.5

# Setup a TCP connection

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

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

$ns connect $tcp $sink $tcp set fid_ 1

# Setup a FTP over TCP connection set ftp [new Application/FTP] $ftp attach-agent $tcp $ftp set type_ FTP

# Setup a UDP connection set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null] $ns attach-agent $n3 $null $ns connect $udp $null $udp set fid_ 2

# Setup a CBR over UDP connection set cbr [new Application/Traffic/CBR] $cbr attach-agent $udp

$cbr set type_ CBR $cbr set packetSize_ 1000 $cbr set rate_ 0.01Mb $cbr set random_ false

(4)

$ns at 0.1 "$cbr start" $ns at 1.0 "$ftp start" $ns at 24.0 "$ftp stop" $ns at 24.5 "$cbr stop" $ns at 25.5.0 "finish" $ns run

3.Simulate the different type of internet traffic such as FTP

and TELNET over a network and analyze the throughput.

#Create Simulator

set ns [new Simulator]

#Open Trace and NAM Trace File

set ntrace [open prog3.tr w]

$ns trace-all $ntrace

set namfile [open prog3.nam w]

$ns namtrace-all $namfile

#Finish Procedure

proc Finish {} {

global ns ntrace namfile

#Dump all trace data and close the files

$ns flush-trace

close $ntrace

close $namfile

(5)

exec nam prog3.nam &

#Calculate throughput = (number of packets received/time taken for

simulation)

set numTcp [exec grep "^r" prog3.tr | grep "tcp" | tail -n 1 | cut -d " " -f

6]

set TcpSize [exec grep "^r" prog3.tr | grep -c "tcp"]

set tcpTime 24.0

set numUdp [exec grep "^r" prog3.tr | grep "udp" | tail -n 1 | cut -d " "

-f 6]

set UdpSize [exec grep "^r" prog3.tr | grep -c "udp"]

set udpTime 23.9

puts "The throughput of FTP is "

puts "[expr ($numTcp*$TcpSize)/$tcpTime] bytes per second"

puts "The throughput of Telnet is "

puts "[expr ($numUdp*$UdpSize)/$udpTime] bytes per second"

exit 0

}

#Create four nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

#Create links between the nodes

$ns duplex-link $n0 $n2 2Mb 10ms DropTail

$ns duplex-link $n1 $n2 2Mb 10ms DropTail

$ns simplex-link $n2 $n3 1Mb 10ms DropTail

$ns simplex-link $n3 $n2 1Mb 10ms DropTail

(6)

#Set queue size and Monitor the queue

$ns queue-limit $n0 $n2 10

$ns simplex-link-op $n0 $n2 queuePos 0.5

#Set TCP Connection between n0 and n3

set tcp0 [new Agent/TCP]

$ns attach-agent $n0 $tcp0

set sink0 [new Agent/TCPSink]

$ns attach-agent $n3 $sink0

$ns connect $tcp0 $sink0

#Attach FTP Application over TCP

set ftp0 [new Application/FTP]

$ftp0 attach-agent $tcp0

$ftp0 set type_ FTP

#Set UDP Connection between n1 and n3

set udp0 [new Agent/UDP]

$ns attach-agent $n1 $udp0

set null0 [new Agent/Null]

$ns attach-agent $n3 $null0

$ns connect $udp0 $null0

#Attach Telnet Application over UDP

set telnet [new Application/Telnet]

$telnet attach-agent $udp0

$telnet set type_ Telnet

#Schedule Events

$ns at 0.1 "$telnet start"

$ns at 0.5 "$ftp0 start"

$ns at 24.0 "$telnet stop"

$ns at 24.5 "$ftp0 stop"

$ns at 25.0 "Finish"

(7)

#Run Simulation

$ns run

4. Simulate a transmission of ping message over a network topology

consisting of 6 nodes and find the number of packets dropped due to

congestion.

#Create a simulator object

set ns [new Simulator]

#Open a trace file

set nf [open exp4.nam w]

$ns namtrace-all $nf

set nd [open exp4.tr w]

$ns trace-all $nd

$ns color 1 Red

$ns color 2 Green

#Define a 'finish' procedure

proc finish {} {

global ns nf nd

$ns flush-trace

close $nf

close $nd

exec nam exp4.nam &

exit 0

(8)

#Create six nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

set n4 [$ns node]

set n5 [$ns node]

#Connect the nodes with two links

$ns duplex-link $n0 $n1 0.1Mb 10ms DropTail

$ns duplex-link $n1 $n2 0.1Mb 10ms DropTail

$ns duplex-link $n2 $n3 0.1Mb 10ms DropTail

$ns duplex-link $n3 $n4 0.1Mb 10ms DropTail

$ns duplex-link $n4 $n5 0.1Mb 10ms DropTail

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

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

$ns duplex-link-op $n2 $n3 orient down

$ns duplex-link-op $n3 $n4 orient left

$ns duplex-link-op $n4 $n5 orient left

#Define a 'recv' function for the class 'Agent/Ping'

Agent/Ping instproc recv {from rtt} {

$self instvar node_

puts "node [$node_ id] received ping answer from \

#$from with round-trip-time $rtt ms."

}

#Create two ping agents and attach them to the nodes n0 and n2

set p0 [new Agent/Ping]

$ns attach-agent $n0 $p0

$p0 set fid_ 1

(9)

$ns attach-agent $n5 $p1

$p1 set fid_ 2

#Connect the two agents

$ns connect $p0 $p1

#Schedule events

$ns at 0.2 "$p0 send"

$ns at 0.4 "$p1 send"

$ns at 0.6 "$p0 send"

$ns at 0.8 "$p1 send"

$ns at 1.0 "finish"

#Run the simulation

$ns run

5.Simulate an Ethernet LAN using n nodes (6 ), change error rate and

data rate and compare the throughput.

#Create Simulator set ns [new Simulator]

#Use colors to differentiate the traffic $ns color 1 Blue

$ns color 2 Red

#Open trace and NAM trace file set ntrace [open prog5.tr w]

(10)

$ns trace-all $ntrace

set namfile [open prog5.nam w] $ns namtrace-all $namfile

#Finish Procedure proc Finish {} {

global ns ntrace namfile

#Dump all trace data and close the files $ns flush-trace

close $ntrace close $namfile

#Execute the nam animation file exec nam prog5.nam &

#Calculate the throughput = (number of packets received/time taken for simulation) set TcpSize [exec grep "^r" prog5.tr | grep "tcp" | tail -n 1 | cut -d " " -f 6]

set numTcp [exec grep "^r" prog5.tr | grep -c "tcp"] set tcpTime 123.0

set UdpSize [exec grep "^r" prog5.tr | grep "cbr" | tail -n 1 | cut -d " " -f 6] set numUdp [exec grep "^r" prog5.tr | grep -c "cbr"]

set udpTime 124.4

puts "The throughput of FTP is"

puts "[expr ($numTcp*$TcpSize)/$tcpTime] bytes per second" puts "The throughput of CBR is"

puts "[expr ($numUdp*$UdpSize)/$udpTime] bytes per second" exit 0

}

#Create 6 nodes

for {set i 0} {$i < 6} {incr i} { set n($i) [$ns node]

}

#Create duplex links between the nodes

$ns duplex-link $n(0) $n(2) 2Mb 10ms DropTail $ns duplex-link $n(1) $n(2) 2Mb 10ms DropTail $ns simplex-link $n(2) $n(3) 0.3Mb 100ms DropTail $ns simplex-link $n(3) $n(2) 0.3Mb 100ms DropTail

(11)

#Node n(3), n(4) and n(5) are considered in a LAN

set lan [$ns newLan "$n(3) $n(4) $n(5)" 0.5Mb 40ms LL Queue/DropTail MAC/802_3 Channel]

#Orientation to the nodes

$ns duplex-link-op $n(0) $n(2) orient right-down $ns duplex-link-op $n(1) $n(2) orient right-up $ns simplex-link-op $n(2) $n(3) orient right

#Setup queue between n(2) and n(3) and monitor the queue $ns queue-limit $n(2) $n(3) 20

$ns simplex-link-op $n(2) $n(3) queuePos 0.5

#Set error model on link n(2) and n(3) and insert the error model set loss_module [new ErrorModel]

$loss_module ranvar [new RandomVariable/Uniform] $loss_module drop-target [new Agent/Null]

$ns lossmodel $loss_module $n(2) $n(3)

#Setup TCP Connection between n(0) and n(4) set tcp0 [new Agent/TCP/Newreno]

$tcp0 set fid_ 1

$tcp0 set window_ 8000 $tcp0 set packetSize_ 552 $ns attach-agent $n(0) $tcp0

set sink0 [new Agent/TCPSink/DelAck] $ns attach-agent $n(4) $sink0

$ns connect $tcp0 $sink0

#Apply FTP Application over TCP set ftp0 [new Application/FTP] $ftp0 set type_ FTP

$ftp0 attach-agent $tcp0

#Setup UDP Connection between n(1) and n(5) set udp0 [new Agent/UDP]

$udp0 set fid_ 2

$ns attach-agent $n(1) $udp0 set null0 [new Agent/Null]

(12)

$ns attach-agent $n(5) $null0 $ns connect $udp0 $null0

#Apply CBR Traffic over UDP

set cbr0 [new Application/Traffic/CBR] $cbr0 set type_ CBR

$cbr0 set packetSize_ 1000 $cbr0 set rate_ 0.1Mb $cbr0 set random_ false $cbr0 attach-agent $udp0 #Schedule events $ns at 0.1 "$cbr0 start" $ns at 1.0 "$ftp0 start" $ns at 124.0 "$ftp0 stop" $ns at 124.5 "$cbr0 stop" $ns at 125.0 "Finish" #Run Simulation $ns run Output: #ns prog5.tcl The throughput of FTP is

72556.097560975613 bytes per second The throughput of CBR is

37363.34405144694 bytes per second

6. Simulate an Ethernet LAN using n nodes and set multiple traffic

nodes and determine the collision across different nodes.

#Create Simualator

set ns [new Simulator]

(13)

#Use colors to differentiate the traffics

$ns color 1 Blue

$ns color 2 Red

#Open trace and NAM trace file

set ntrace [open prog6.tr w]

$ns trace-all $ntrace

set namfile [open prog6.nam w]

$ns namtrace-all $namfile

#Finish Procedure

proc Finish {} {

global ns ntrace namfile

#Dump all trace data and close the files

$ns flush-trace

close $ntrace

close $namfile

#Execute the NAM animation file

exec nam prog6.nam &

#Calculate the number of packets dropped due to collision

puts "The number of packet drops due to collision is"

exec grep "^d" prog6.tr | cut -d " " -f 4 | grep -c "3" &

exit 0

}

#Create 6 nodes

for {set i 0} {$i < 6} {incr i} {

set n($i) [$ns node]

}

#Create duplex links between the nodes

$ns duplex-link $n(0) $n(2) 2Mb 10ms DropTail

$ns duplex-link $n(1) $n(2) 2Mb 10ms DropTail

(14)

$ns duplex-link $n(2) $n(3) 0.2Mb 100ms DropTail

#Nodes n(3), n(4) and n(5) are considered in a LAN

set lan0 [$ns newLan "$n(3) $n(4) $n(5)" 0.5Mb 40ms LL

Queue/DropTail MAC/802_3 Channel]

#Orientation to the nodes

$ns duplex-link-op $n(0) $n(2) orient right-down

$ns duplex-link-op $n(1) $n(2) orient right-up

$ns duplex-link-op $n(2) $n(3) orient right

#Set up queue between n(2) and n(3) and monitor the queue

$ns queue-limit $n(2) $n(3) 20

$ns simplex-link-op $n(2) $n(3) queuePos 0.5

#Setup TCP connection between n(0) and n(4)

set tcp0 [new Agent/TCP/Newreno]

$ns attach-agent $n(0) $tcp0

set sink0 [new Agent/TCPSink/DelAck]

$ns attach-agent $n(4) $sink0

$ns connect $tcp0 $sink0

$tcp0 set fid_ 1

$tcp0 set window_ 8000

$tcp0 set packetSize_ 552

#Apply FTP application over TCP

set ftp0 [new Application/FTP]

$ftp0 attach-agent $tcp0

$ftp0 set type_ FTP

#Setup another TCP connection between n(5) and n(1)

set tcp1 [new Agent/TCP/Newreno]

$ns attach-agent $n(5) $tcp1

set sink1 [new Agent/TCPSink/DelAck]

$ns attach-agent $n(1) $sink1

(15)

$ns connect $tcp1 $sink1

$tcp1 set fid_ 2

$tcp1 set window_ 8000

$tcp1 set packetSize_ 552

#Apply FTP application over TCP

set ftp1 [new Application/FTP]

$ftp1 attach-agent $tcp1

$ftp1 set type_ FTP

#Schedule the events

$ns at 0.1 "$ftp0 start"

$ns at 0.2 "$ftp1 start"

$ns at 24.8 "$ftp0 stop"

$ns at 24.9 "$ftp1 stop"

$ns at 25.0 "Finish"

#Run the simulation

$ns run

7. Simulate an Ethernet LAN using n nodes and set multiple traffic

nodes and plot congestion window for different source/destination

#Create Simulator set ns [new Simulator]

#Use colors to differentiate the traffics $ns color 1 Blue

$ns color 2 Red

#Open trace and NAM trace file set ntrace [open prog7.tr w]

(16)

$ns trace-all $ntrace

set namfile [open prog7.nam w] $ns namtrace-all $namfile

#Use some flat file to create congestion graph windows set winFile0 [open WinFile0 w]

set winFile1 [open WinFile1 w]

#Finish Procedure proc Finish {} {

#Dump all trace data and Close the files global ns ntrace namfile

$ns flush-trace close $ntrace close $namfile

#Execute the NAM animation file exec nam prog7.nam &

Plot the Congestion Window graph using xgraph exec xgraph WinFile0 WinFile1 &

exit 0 }

#Plot Window Procedure

proc PlotWindow {tcpSource file} { global ns

set time 0.1

set now [$ns now]

set cwnd [$tcpSource set cwnd_] puts $file "$now $cwnd"

$ns at [expr $now+$time] "PlotWindow $tcpSource $file" }

#Create 6 nodes

for {set i 0} {$i<6} {incr i} { set n($i) [$ns node]

}

(17)

$ns duplex-link $n(0) $n(2) 2Mb 10ms DropTail $ns duplex-link $n(1) $n(2) 2Mb 10ms DropTail $ns duplex-link $n(2) $n(3) 0.6Mb 100ms DropTail

#Nodes n(3) , n(4) and n(5) are considered in a LAN

set lan [$ns newLan "$n(3) $n(4) $n(5)" 0.5Mb 40ms LL Queue/DropTail MAC/802_3 Channel]

#Orientation to the nodes

$ns duplex-link-op $n(0) $n(2) orient right-down $ns duplex-link-op $n(1) $n(2) orient right-up $ns duplex-link-op $n(2) $n(3) orient right

#Setup queue between n(2) and n(3) and monitor the queue $ns queue-limit $n(2) $n(3) 20

$ns duplex-link-op $n(2) $n(3) queuePos 0.5

#Set error model on link n(2) to n(3) set loss_module [new ErrorModel]

$loss_module ranvar [new RandomVariable/Uniform] $loss_module drop-target [new Agent/Null]

$ns lossmodel $loss_module $n(2) $n(3)

#Set up the TCP connection between n(0) and n(4) set tcp0 [new Agent/TCP/Newreno]

$tcp0 set fid_ 1

$tcp0 set window_ 8000 $tcp0 set packetSize_ 552 $ns attach-agent $n(0) $tcp0

set sink0 [new Agent/TCPSink/DelAck] $ns attach-agent $n(4) $sink0

$ns connect $tcp0 $sink0

#Apply FTP Application over TCP set ftp0 [new Application/FTP] $ftp0 attach-agent $tcp0 $ftp0 set type_ FTP

(18)

#Set up another TCP connection between n(5) and n(1) set tcp1 [new Agent/TCP/Newreno]

$tcp1 set fid_ 2

$tcp1 set window_ 8000 $tcp1 set packetSize_ 552 $ns attach-agent $n(5) $tcp1

set sink1 [new Agent/TCPSink/DelAck] $ns attach-agent $n(1) $sink1

$ns connect $tcp1 $sink1

#Apply FTP application over TCP set ftp1 [new Application/FTP] $ftp1 attach-agent $tcp1 $ftp1 set type_ FTP #Schedule Events $ns at 0.1 "$ftp0 start" $ns at 0.1 "PlotWindow $tcp0 $winFile0" $ns at 0.5 "$ftp1 start" $ns at 0.5 "PlotWindow $tcp1 $winFile1" $ns at 25.0 "$ftp0 stop" $ns at 25.1 "$ftp1 stop" $ns at 25.2 "Finish"

#Run the simulation $ns run

X

PART B

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

(19)

char m[50],g[50],r[50],q[50],temp[50]; void caltrans(int); void crc(int); void calram(); void shiftl(); int main() { int n,i=0; char ch,flag=0;

printf("Enter the frame bits:"); while((ch=getc(stdin))!='\n') m[i++]=ch; n=i; for(i=0;i<16;i++) m[n++]='0'; m[n]='\0';

printf("Message after appending 16 zeros:%s",m); for(i=0;i<=16;i++) g[i]='0'; g[0]=g[4]=g[11]=g[16]='1';g[17]='\0'; printf("\ngenerator:%s\n",g); crc(n); printf("\n\nquotient:%s",q); caltrans(n); printf("\ntransmitted frame:%s",m); printf("\nEnter transmitted freme:"); scanf("\n%s",m); printf("CRC checking\n"); crc(n); printf("\n\nlast remainder:%s",r); for(i=0;i<16;i++) if(r[i]!='0') flag=1; else continue; if(flag==1)

printf("Error during transmission"); else

(20)

} void crc(int n) { int i,j; for(i=0;i temp[i]=m[i]; for(i=0;i<16;i++) r[i]=m[i]; printf("\nintermediate remainder\n"); for(i=0;i { if(r[0]=='1') { q[i]='1'; calram(); } else { q[i]='0'; shiftl(); } r[16]=m[17+i]; r[17]='\0'; printf("\nremainder %d:%s",i+1,r); for(j=0;j<=17;j++) temp[j]=r[j]; } q[n-16]='\0'; } void calram() { int i,j; for(i=1;i<=16;i++) r[i-1]=((int)temp[i]-48)^((int)g[i]-48)+48; } void shiftl() { int i; for(i=1;i<=16;i++) r[i-1]=r[i];

(21)

} void caltrans(int n) { int i,k=0; for(i=n-16;i m[i]=((int)m[i]-48)^((int)r[k++]-48)+48; m[i]='\0'; }

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

#include struct frame { int fslno; char finfo[20]; };

struct frame arr[10]; int n;

void sort() {

int i,j,ex;

struct frame temp; for(i=0;i { ex=0; for(j=0;j if(arr[j].fslno>arr[j+1].fslno) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; ex++; } if(ex==0)

(22)

break; } } int main() { int i; system("clear"); printf("enter no of frames\n"); scanf("%d",&n);

printf("enter frame sequence no and frame contents\n"); for(i=0;i scanf("%d%s",&arr[i].fslno,&arr[i].finfo); sort(); printf("frames in sequence\n"); for(i=0;i { printf("01111110 %d lt %s 01111110\n",arr[i].fslno,arr[i].finfo); } }

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

for transmission

#include #define nul 1000 #define nodes 10 int no; struct node { int a[nodes][4]; }router[nodes];

(23)

void init(int r) { int i; for(i=1;i<=no;i++) { router[r].a[i][1]=i; router[r].a[i][2]=999; router[r].a[i][3]=nul; } router[r].a[r][2]=0; router[r].a[r][3]=r; } void inp(int r) { int i;

printf("\nEnter dist from the node %d to other nodes",r); printf("\nPls enter 999 if there is no direct route\n",r); for(i=1;i<=no;i++)

{ if(i!=r) {

printf("\nEnter dist to the node %d:",i); scanf("%d",&router[r].a[i][2]); router[r].a[i][3]=i; } } } void display(int r) { int i,j;

printf("\n\nThe routing table for node %d is as follows:",r); for(i=1;i<=no;i++)

{

if(router[r].a[i][2]>=999)

printf("\n\t\t\t %d \t no link \t no hop",router[r].a[i][1]); else

printf("\n\t\t\t %d \t %d \t\t d",router[r].a[i][1],router[r].a[i] [2],router[r].a[i][3]);

(24)

} } void dv_algo(int r) { int i,j,z; for(i=1;i<=no;i++) {

if(router[r].a[i][2]!=999 && router[r].a[i][2]!=0) { for(j=1;j<=no;j++) { z=router[r].a[i][2]+router[i].a[j][2]; if(router[r].a[j][2]>z) { router[r].a[j][2]=z; router[r].a[j][3]=i; } } } } } int main() { int i,j,x,y; char choice;

printf("Enter the no. of nodes required (less than 10 pls):"); scanf("%d",&no); for(i=1;i<=no;i++) { init(i); inp(i); }

printf("\nThe configuration of the nodes after initialization is as follows:"); for(i=1;i<=no;i++)

display(i);

for(i=1;i<=no;i++) dv_algo(i);

(25)

for(i=1;i<=no;i++) display(i);

while(1) {

printf("\n\nWanna continue (y/n):"); scanf("%c",&choice);

if(choice=='n') break;

printf("\nEnter the nodes btn which shortest path is to be found:\n"); scanf("%d %d",&x,&y);

printf("\nThe length of the shortest path is %d",router[x].a[y][2]); }

}

4. Write a program for spanning tree algorithm to find loop less path

#include #include

#define MAX 20

#define INFINITY 999 enum boolean {false,true};

void prim(int c[][MAX],int t[MAX],int n); int mincost=0;

int main() {

int n,c[MAX][MAX],t[2*(MAX-1)]; int i,j;

printf("this pgm implements prim's algom\n"); printf("how many nodes does the graph have?\n"); scanf("%d",&n);

printf("enter cost adjacency matrix\n"); printf("999 indicates no connection\n"); for(i=0;i

for(j=0;j

(26)

prim(c,t,n); printf("spanning tree\n"); for(i=0;i<2*(n-1);i+=2) printf("%d%d\n",t[i]+1,t[i+1]+1); printf("mincost=%d",mincost); return 0; }

void prim(int c[][MAX],int t[MAX],int n) {

int i,j;

enum boolean v[MAX]; int u,s,min,v1,v2; for(i=0;i v[i]=false; v[0]=true; u=0; t[u]=1; s=0; u++; while(u { min=INFINITY; for(i=0;i for(j=1;j if(v[i]==true&&v[j]==false&&c[i][j] { min=c[i][j]; v1=i; v2=j; } mincost=mincost+min; if(min==INFINITY) {

printf("graph disconnected:spanning tree impossible\n"); exit(1); } v[v2]=true; u++; t[s++]=v1; t[s++]=v2; } }

(27)

client send the name of a file and server to send back the contents of

the requested file if present.

Client Side: #include #include #include #include #include

int main(int argc,char *argv[]) {

int sockfd,newsockfd,portno,len,n; char buffer[256],c[20000];

struct sockaddr_in serv,cli; FILE *fd;

if(argc<2) {

printf("Err:no port no.\nusage:\n./client portno\n ex:./client 7777\n"); exit(1); } sockfd=socket(AF_INET,SOCK_STREAM,0); bzero((char *)&serv,sizeof(serv)); portno=atoi(argv[1]); serv.sin_family=AF_INET; serv.sin_port=htons(portno);

if(connect(sockfd,(struct sockaddr *)&serv,sizeof(serv))<0) {

printf("server not responding..\n\n\n\ti am to terminate\n"); exit(1);

}

printf("Enter the file with complete path\n"); scanf("%s",&buffer);

if(write(sockfd,buffer,strlen(buffer))<0) printf("Err writing to socket..\n");

bzero(c,2000);

printf("Reading..\n..\n"); if(read(sockfd,c,1999)<0) printf("error: read error\n");

(28)

fputs(c,stdout); printf("\n..\n"); return 0; } Server Side: #include #include #include #include #include

int main(int argc,char *argv[]) {

int sockfd,newsockfd,portno,len,n; char buffer[256],c[2000],cc[20000]; struct sockaddr_in serv,cli;

FILE *fd; if(argc<2) {

printf("erroe:no port no\n usage:\n/server port no\n"); exit(1); } sockfd=socket(AF_INET,SOCK_STREAM,0); portno=atoi(argv[1]); serv.sin_family=AF_INET; serv.sin_addr.s_addr=INADDR_ANY; serv.sin_port=htons(portno);

bind(sockfd,(struct sockaddr *)&serv,sizeof(serv)); listen(sockfd,10);

len=sizeof(cli);

printf("serve:\nwaiting for connection\n");

newsockfd=accept(sockfd,(struct sockaddr *)&cli,&len); bzero(buffer,255);

n=read(newsockfd,buffer,255); printf("\nserver recv:%s\n",buffer); if((fd=fopen(buffer,"r"))!=NULL) {

(29)

printf("server:%s found\n opening and reading..\n",buffer); printf("reading..\n..reading complete"); fgets(cc,2000,fd); while(!feof(fd)) { fgets(c,2000,fd); strcat(cc,c); } n=write(newsockfd,cc,strlen(cc)); if(n<0)

printf("error writing to socket"); printf("\ntransfer complete\n"); }

else {

printf("server:file not found\n");

n=write(newsockfd,"file not foung",15); if(n<0)

printf("error: writing to socket..\n"); }

return 0; }

mplement the above program using as Message queue or FIFOs as IPC

channel.

Server Side:

#include #include #include

#define fifo1 "fifo1" #define fifo2 "fifo2" int main()

{

(30)

int fd1,fd2,fd,i; for(i=0;i<100;i++) c[i]=p[i]='\0';

mknod(fifo1,S_IFIFO|0777,0); mknod(fifo2,S_IFIFO|0777,0);

printf("server online\n waiting for request...\n"); fd1=open(fifo1,O_RDONLY);

read(fd1,p,100);

if((fd=open(p,O_RDONLY))<0) {

printf("\n server:file %s not found\n",p); exit(1);

}

printf("\n server:%s found!\n transfering the content"); read(fd,c,1000); fd2=open(fifo2,O_WRONLY); write(fd2,c,strlen(c)); printf("server:transfer completed\n"); }

Client Side:

#include #include #include

#define fifo1 "fifo1" #define fifo2 "fifo2"

int main() { char p[100],c[100],ch; int fd1,fd2,fd,i; for(i=0;i<100;i++) c[i]=p[i]='\0'; mknod(fifo1,S_IFIFO|0777,0); mknod(fifo2,S_IFIFO|0777,0); printf("waiting for server"); fd1=open(fifo1,O_WRONLY);

(31)

printf("server is online\n client enter the path"); i=0; while(1) { ch=getchar(); if(ch=='\n') break; p[i++]=ch; } p[i]='\0'; write(fd1,p,strlen(p)); if((fd=open(p,O_RDONLY))<0) {

printf("error file not found!enter valid path name\n\n",p); exit(1);

}

fd2=open(fifo2,O_RDONLY); read(fd2,c,1000);

printf("File Recieved:Display Contents"); fputs(c,stdout);

printf("\n\n"); }

7. Write a program for simple RSA algorithm to encrypt and decrypt

the data

#include #include #include #include

(32)

unsigned long modexp(unsigned long msg,unsigned long exp,unsigned long n) {

unsigned long i,k=1; for(i=0;i k=(k*msg)%n; return k; } int main() {

unsigned long p,q,e,d,n,z,i,C,M; int len;

char data[100]; system("clear");

printf("Enter the value of P and Q (such that p*q>255 and p not equal to q)\n"); scanf("%lu%lu",&p,&q); n=p*q; z=(p-1)*(q-1); for(i=1;i { if((z%i)==0) continue; else break; } e=i;

printf("\nEncryption key is :%lu",e); for(i=1;i

if(((e*i-1)%z)==0) break;

d=i;

printf("\ndecryption key is :%lu",d); printf("\npls enter the message:"); scanf("%s",data); len=strlen(data); for(i=0;i { M=(unsigned long)data[i]; C=modexp(M,e,n);

(33)

M=modexp(C,d,n);

printf("\ndecrypted value and its char representation:%lu\t%c\n",M,M); }

return 0; }

8. Write a program for hamming code generation for error

detection/correction

Encoding.

#include #include #include int gmatrix[4][7]={0,1,1,1,0,0,0, 1,0,1,0,1,0,0, 1,1,1,0,0,1,0, 1,1,1,0,0,0,1}; char data[5]; int encode[8]; int con(char x); int main() { int i,j; system("clear");

printf("Enter the Hamming code\n"); scanf("%s",&data); for(i=0;i<7;i++) for(j=0;j<4;j++) encode[i]=encode[i]+con(data[j])*gmatrix[j][i]; puts(" ENCODE"); for(i=0;i<7;i++) {

(34)

encode[i]=encode[i]%2; printf("%i",encode[i]); } puts(" "); return 0; } int con(char x) { if(x == '1') return 1; else return 0; } Decoding #include #include #include int hmatrix[3][7]={1,0,0,0,1,1,1, 0,1,0,1,0,1,1, 0,0,1,1,1,0,1}; char edata[8]; int syndrome[3]; int errdig; int con(char x) { if(x=='1') return 1; else return 0; } int main()

(35)

{

int i,j,err;

system("system");

printf("\nEnter the encoded bit\n"); scanf("%s",edata); for(i=0;i<3;i++) for(j=0;j<7;j++) syndrome[i]=syndrome[i]+con(edata[j])*hmatrix[i][j]; for(i=0;i<3;i++) syndrome[i]=syndrome[i]%2; err=4*syndrome[0]+2*syndrome[1]+1*syndrome[2]; printf("\nhi...%d\n",err); if(0==err)

printf("\nError free data\n"); else { switch(err) { case 4:errdig=1; break; case 3:errdig=4; break; case 1:errdig=3; break; default:errdig=err; }

printf("\nError in bit %d----%c",errdig,edata[errdig]); errdig--; if('1'==edata[errdig]) edata[errdig]='0'; else edata[errdig]='1'; }

printf("\nThe data is:"); for(i=3;i<7;i++)

printf("%c",edata[i]); puts(" ");

(36)

9. Write a program for congestion control using Leaky Bucket

algorithm

#include #define buffersize 10 struct buff { int pno;

struct buff *link; };

struct buff *front,*rear,*temp;

main() { front=NULL; rear=NULL; int n=0,i,timer=0,npacks=0; for(i=1;i<=buffersize;i++) { n++; insert(n); npacks++; } while(n<20) { n++; if(timer==5) { delete(); npacks--; if(npacks<=10) insert(n); timer=0; } else

(37)

{ printf("\nPacket %d is discarded..\n",n); timer++; sleep(1); } } } insert(int n) {

struct buff *temp; if(front==NULL) {

printf("\nPacket %d is queued..\n",n);

temp=(struct buff*)malloc(sizeof(struct buff)); temp->pno=n; temp->link=NULL; front=temp; rear=temp; } else { printf("\npacket %d queued..\n",n);

temp=(struct buff*)malloc(sizeof(struct buff)); temp->pno=n; temp->link=NULL; rear->link=temp; rear=temp; } } delete() {

struct buff *temp; if(front==NULL) printf("\nBuffer is empty..\n"); else { temp=front; printf("\nPacket %d id deleted",temp->pno); front=front->link; free(temp);

(38)

} }

Illustration of Wifi communication range

Consider a Wifi access point (AP) and a base station (STA), which are both static. The STA can

communicate with the AP only when it is within a certain distance from the AP. Beyond that range,

the two nodes can't receive each others signals.

Given below is a code to simulate the said scenario with ns3. STA sends a packet to the AP; AP

echoes it back to the base station. The AP is located at position (x, y) = (0, 0). STA is at (xDistance,

0) (all distances in meter). Default value of xDistance is set to 10. [Lines #76, #131]

Increase the value of xDistance in the code and find out the maximum distance upto which

two way communication is possible. This can be verified from the output of the code, which

will show the STA has received reply from the AP (indicated by IP address).

If you like playing with code, you can also try these:

Change IP address allocated to the nodes [Line #146]

Run the UDP echo server on a different port [Line #151]

Send more packets from the echo client [Line #159]

Position the nodes along the y-axis [Line #126]

/*

* This program is free software; you can redistribute it and/or modify

* it under the terms of the GNU General Public License version 2 as

* published by the Free Software Foundation;

*

* This program is distributed in the hope that it will be useful,

(39)

* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

* GNU General Public License for more details.

*

* You should have received a copy of the GNU General Public License

* along with this program; if not, write to the Free Software

* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

*/

// Default Network Topology

//

// Wifi 10.1.1.0

// AP

// * *

// | |

// n1 n0

//

// Node #0 is the AP, #1 is a base station

// #1 sends UDP echo mesg to the AP; AP sends a UDP response back to the node

// Communication is possible only when the station is within a certain distance from the AP

#include "ns3/core-module.h"

#include "ns3/simulator-module.h"

#include "ns3/node-module.h"

#include "ns3/helper-module.h"

#include "ns3/wifi-module.h"

#include "ns3/mobility-module.h"

#include "ns3/ipv4-global-routing-helper.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("Wifi-2-nodes-fixed");

void

PrintLocations (NodeContainer nodes, std::string header)

{

std::cout << header << std::endl;

for(NodeContainer::Iterator iNode = nodes.Begin (); iNode != nodes.End (); ++iNode)

{

Ptr<Node> object = *iNode;

Ptr<MobilityModel> position = object->GetObject<MobilityModel> ();

NS_ASSERT (position != 0);

Vector pos = position->GetPosition ();

std::cout << "(" << pos.x << ", " << pos.y << ", " << pos.z << ")" << std::endl;

}

std::cout << std::endl;

}

(40)

void

PrintAddresses(Ipv4InterfaceContainer container, std::string header)

{

std::cout << header << std::endl;

uint32_t nNodes = container.GetN ();

for (uint32_t i = 0; i < nNodes; ++i)

{

std::cout << container.GetAddress(i, 0) << std::endl;

}

std::cout << std::endl;

}

int

main (int argc, char *argv[])

{

bool verbose = true;

uint32_t nWifi = 2;

/** Change this parameter and verify the output */

double xDistance = 10.0;

CommandLine cmd;

cmd.AddValue ("xDistance", "Distance between two nodes along x-axis", xDistance);

cmd.Parse (argc,argv);

if (verbose)

{

LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO);

LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO);

}

// 1. Create the nodes and hold them in a container

NodeContainer wifiStaNodes,

wifiApNode;

wifiStaNodes.Create (nWifi);

wifiApNode = wifiStaNodes.Get (0);

// 2. Create channel for communication

YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();

YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();

phy.SetChannel (channel.Create ());

WifiHelper wifi = WifiHelper::Default ();

(41)

NqosWifiMacHelper mac = NqosWifiMacHelper::Default ();

// 3a. Set up MAC for base stations

Ssid ssid = Ssid ("ns-3-ssid");

mac.SetType ("ns3::StaWifiMac",

"Ssid", SsidValue (ssid),

"ActiveProbing", BooleanValue (false));

NetDeviceContainer staDevices;

staDevices = wifi.Install (phy, mac, wifiStaNodes.Get (1));

// 3b. Set up MAC for AP

mac.SetType ("ns3::ApWifiMac",

"Ssid", SsidValue (ssid),

"BeaconGeneration", BooleanValue (true),

"BeaconInterval", TimeValue (Seconds (5)));

NetDeviceContainer apDevice;

apDevice = wifi.Install (phy, mac, wifiApNode);

// 4. Set mobility of the nodes

MobilityHelper mobility;

// All space coordinates in meter

mobility.SetPositionAllocator ("ns3::GridPositionAllocator",

"MinX", DoubleValue (0.0),

"MinY", DoubleValue (0.0),

"DeltaX", DoubleValue (xDistance),

"DeltaY", DoubleValue (10.0),

"GridWidth", UintegerValue (3),

"LayoutType", StringValue ("RowFirst"));

mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");

mobility.Install (wifiStaNodes);

// 5.Add Internet layers stack

InternetStackHelper stack;

stack.Install (wifiStaNodes);

// 6. Assign IP address to each device

Ipv4AddressHelper address;

Ipv4InterfaceContainer wifiInterfaces,

wifiApInterface;

address.SetBase ("10.1.1.0", "255.255.255.0");

wifiApInterface = address.Assign (apDevice);

wifiInterfaces = address.Assign (staDevices);

// 7a. Create and setup applications (traffic sink)

(42)

UdpEchoServerHelper echoServer (9); // Port # 9

ApplicationContainer serverApps = echoServer.Install (wifiApNode);

serverApps.Start (Seconds (1.0));

serverApps.Stop (Seconds (4.0));

// 7b. Create and setup applications (traffic source)

UdpEchoClientHelper echoClient (wifiApInterface.GetAddress (0), 9);

echoClient.SetAttribute ("MaxPackets", UintegerValue (1));

echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.)));

echoClient.SetAttribute ("PacketSize", UintegerValue (1024));

ApplicationContainer clientApps = echoClient.Install (wifiStaNodes.Get (1));

clientApps.Start (Seconds (2.0));

clientApps.Stop (Seconds (3.0));

Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

Simulator::Stop (Seconds (4.0));

// 8. Enable tracing (optional)

//phy.EnablePcapAll ("wifi-2-nodes-fixed", true);

PrintAddresses(wifiInterfaces, "IP addresses of base stations");

PrintAddresses(wifiApInterface, "IP address of AP");

PrintLocations(wifiStaNodes, "Location of all nodes");

Simulator::Run ();

Simulator::Destroy ();

return 0;

}

Sample Coding in Wireless

Here Guys this is an sample tcl coding

# Define options

set val(chan) Channel/WirelessChannel ;# channel type

set val(prop) Propagation/TwoRayGround ;# radio-propagation model

set val(netif) Phy/WirelessPhy ;# network interface type

set val(mac) Mac/802_11 ;# MAC type

set val(ifq) Queue/DropTail/PriQueue ;# interface queue type

set val(ll) LL ;# link layer type

set val(ant) Antenna/OmniAntenna ;# antenna model

set val(ifqlen) 50 ;# max packet in ifq

(43)

set val(rp) DSDV ;# routing protocol

set val(x) 1000 ;# X dimension of topography

set val(y) 1000 ;# Y dimension of topography

set val(stop) 150 ;# time of simulation end

set ns [new Simulator]

set tracefd [open simple.tr w]

set namtrace [open simwrls.nam w]

$ns trace-all $tracefd

$ns namtrace-all-wireless $namtrace $val(x) $val(y)

# set up topography object

set topo [new Topography]

$topo load_flatgrid $val(x) $val(y)

create-god $val(nn)

# configure the nodes

$ns node-config -adhocRouting $val(rp) \

-llType $val(ll) \

-macType $val(mac) \

-ifqType $val(ifq) \

-ifqLen $val(ifqlen) \

-antType $val(ant) \

-propType $val(prop) \

-phyType $val(netif) \

-channelType $val(chan) \

-topoInstance $topo \

-agentTrace ON \

-routerTrace ON \

-macTrace OFF \

-movementTrace ON

for {set i 0} {$i < $val(nn) } { incr i } {

set n($i) [$ns node]

}

# Provide initial location of mobilenodes

$n(0) set X_ 347.0

(44)

$n(0) set Z_ 0.0

$n(1) set X_ 345.0

$n(1) set Y_ 36.0

$n(1) set Z_ 0.0

$n(2) set X_ 330.0

$n(2) set Y_ 121.0

$n(2) set Z_ 0.0

$n(3) set X_ 316.0

$n(3) set Y_ 152.0

$n(3) set Z_ 0.0

$n(4) set X_ 246.0

$n(4) set Y_ 90.0

$n(4) set Z_ 0.0

$n(5) set X_ 379.0

$n(5) set Y_ 6.0

$n(5) set Z_ 0.0

# Set a TCP connection between n(1) and n(31)

set tcp [new Agent/TCP/Newreno]

$tcp set class_ 2

set sink [new Agent/TCPSink]

$ns attach-agent $n(1) $tcp

$ns attach-agent $n(31) $sink

$ns connect $tcp $sink

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ns at 10.0 "$ftp start"

# Set a TCP connection between n(31) and n(43)

set tcp [new Agent/TCP/Newreno]

$tcp set class_ 2

set sink [new Agent/TCPSink]

$ns attach-agent $n(31) $tcp

$ns attach-agent $n(43) $sink

$ns connect $tcp $sink

(45)

$ns at 0.0 "$n(0) label CH"

$ns at 0.0 "$n(1) label Source"

#$ns at 0.0 "$n(2) label N2"

$ns at 10.0 "$n(5) setdest 785.0 228.0 5.0"

$ns at 13.0 "$n(26) setdest 700.0 20.0 5.0"

$ns at 15.0 "$n(14) setdest 115.0 85.0 5.0"

#Color change while moving from one group to another

$ns at 73.0 "$n(2) delete-mark N2"

$ns at 73.0 "$n(2) add-mark N2 pink circle"

$ns at 124.0 "$n(11) delete-mark N11"

$ns at 124.0 "$n(11) add-mark N11 purple circle"

$ns at 103.0 "$n(5) delete-mark N5"

$ns at 103.0 "$n(5) add-mark N5 white circle"

$ns at 87.0 "$n(26) delete-mark N26"

$ns at 87.0 "$n(26) add-mark N26 yellow circle"

$ns at 92.0 "$n(14) delete-mark N14"

$ns at 92.0 "$n(14) add-mark N14 green circle"

# Define node initial position in nam

for {set i 0} {$i < $val(nn)} { incr i } {

# 20 defines the node size for nam

$ns initial_node_pos $n($i) 20

}

# Telling nodes when the simulation ends

for {set i 0} {$i < $val(nn) } { incr i } {

$ns at $val(stop) "$n($i) reset";

}

# ending nam and the simulation

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"

$ns at $val(stop) "stop"

$ns at 150.01 "puts \"end simulation\" ; $ns halt"

proc stop {} {

global ns tracefd namtrace

$ns flush-trace

close $tracefd

close $namtrace

exec nam simwrls.nam &

}

(46)

References

Related documents

Results from the South African Solvency Assessment and Management Quantitative Impact Study 1 (SA QIS 1) exercise conducted by the Financial Services Board in 2011 have shown

This listing of sampling units may consist of a list of the names of farm operators obtained through an agricultural census, of households (derived from a population and

Recognizing the need to develop a systematic approach within the Virginia Department of Transportation for addressing events that impact the project schedule, the VDOT – Virginia

Jo enjoys performing the full scope of oral and maxillofacial surgery, including third molar removal, dental implants and bone grafting, orthognathic surgery, tumor and

From the United Religious, Military and Masonic Orders of the Temple the Provincial Prior for Kent Right Eminent Knight Kessick John Jones who is also the Grand

Note that even though LISF is a “blind” policy (a policy that requires, at the time of routing deci- sion, none or minimal information on the parameters.. of the system or the

The extraordinary general meeting of the shareholders of the Company held on 8 April 2014 elected Tomas Salajka to the Board of Directors until the annual general meeting

 Remove Software overheads in I/O path  Increase parallelism on the Target side  Temporal merge for RDMA data transfer.  Implement the optimized SAN as