Ns2 Scripts
Ns2 Scripts
proc finish {} {
global nf ns tr
$ns flush-trace
close $tr
exec nam out.nam &
exit 0
}
$ns run
proc finish {} {
global nf ns tr
$ns flush-trace
close $tr
exec nam out.nam &
exit 0
}
$ns rtproto DV
$ns run
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
$ns run
proc finish {} {
global ns nf nt
$ns flush-trace
close $nf
close $nt
exec nam out.nam &
exit 0
}
$ns run
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
$ns run
This would set the simulator with the simulator object which is to be accessed in the script.
This would set the nam file (network animation file) with the object and connect to ns.
This would set the trace file and would connect to the simulator. The trace file is required to analyze the
various packets which are send, received type of application used etc.
Now the nodes could be set as many as you want, for loop could be used if many nodes are to be made.
The connection for the various nodes with each other with the band width and rate.
The nodes could be given with various orientations with this option. right, right-up and right down could be
used depending on the node.
For the application like tcp or udp to run, we need to set two agents and the application which should run
in between.
When using tcp, we have ftp as the application and tcpsink as the end agent. connection must be made
between tcp and tcpsink, same in udp with cbr and null respectively.
This would make a tcp agent and connect it with the node.
set ftp [new Application/FTP]
$ftp attach-agent $tcp
Now the tcpsink is set to a node where the tcp packets are received.
The tcp and sink (agents) needs to be connected, such that the network flows.
We can use the routing protocols in the simulator using rtmodel (to break the link), rtproto (to use the
protocol)
$ns rtproto DV
$ns rtproto LS
When all this is done the tcp could be started at some point and could call the finish procedure to end.
The out.tr file is used to trace the packets. A normal awk command could be used to analyse the packets.
We could also stop the tcp or udp in between using stop instead of start, hence nam out.nam need to be
used if finish is not used.
$ns run
The file should be saved in .tcl format and should use ns filename.tcl to run
#Monitor the queue for the link between node 2 and node 3
$ns duplex-link-op $n2 $n3 queuePos 0.5
$ns rtproto DV
#Open the Trace file
set file1 [open out.tr w]
$ns trace-all $file1
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
# S(1) ----
# . |
# . |
# S(NodeNb) ----
# We define three files that will be used to trace the queue size,
# Number of sources
set NodeNb 6
}
}
#Connections
#FTP sources
$rng1 seed 0
$rng2 seed 0
# Random inter-arrival times of TCP transfer at each source i
# We now define the beginning times of transfers and the transfer sizes
set Conct($i,$j) $t
# it has ended. The procedure calls itself each 0.1 sec (this is
proc Test {} {
global Conct tcpsrc Size NodeNb NumberFlows ns RV ftp Out tcp_snk RVSize
countFlows $i 0
$tcpsrc($i,$j) reset
$tcp_snk($i,$j) reset
}}}}
set Cnts($j) 0
# 3 (in which case the "ind" parameter does not play a role). The
} else {
set sum 0
proc finish {} {
$ns flush-trace
close $qsize
close $qbw
close $qlost
# Execute xgraph to display the queue size, queue bandwidth and loss rate
exec xgraph queuesize.tr -geometry 800x400 -t "Queue size" -x "secs" -y "# packets" &
exec xgraph queuebw.tr -geometry 800x400 -t "bandwidth" -x "secs" -y "Kbps" -fg white &
exec xgraph queuelost.tr -geometry 800x400 -t "# Packets lost" -x "secs" -y "packets" -fg red &
exit 0
####################
# QUEUE MONiTORiNG #
####################
# The following procedure records queue size, bandwidth and loss rate
proc record {} {
$ns at 20 "finish"
$ns run
proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exit 0
set NumbSrc 5
set Duration 10
#Source nodes
# Create a random generator for starting the ftp and for bottleneck link delays
$rng seed 0
# paratmers for random variables for delays
#TCP Sources
#TCP Destinations
#Connections
}
#FTP sources
global ns
$ns run
# wrls1.tcl
# Define options
create-god $val(nn)
-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
# Generation of movements
global ns
proc stop {} {
$ns flush-trace
close $tracefd
close $namtrace
}
$ns run
proc finish {} {
$ns flush-trace
close $file1
close $file2
exit 0
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel]
global ns
# PPP
$ns run
set ns [new Simulator]
proc finish {} {
$ns flush-trace
close $file1
close $file2
exit 0
}
#Create six nodes
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/802_3 Channel]
global ns
# PPP
$ns run
Hello File Descriptors
1
/* Not stdio.h */
2
#include <unistd.h>
3
4
void main()
5
{
6
char str[100];
7
8 /*Write on screen*/
10
12 read(0,str,100);
13
write(1,"\nYou typed :\n",13);
14
15
/*write 10 chars from 'str' to screen */
16
write(1,str,10);
17
18
/*newline*/
19
write(1,"\n",1);
20
}
21
2
3 You typed :
4 hi how are
read/write
1 write(int fd, const void *buf, size_t n);
2
#include <sys/types.h>
3
#include <sys/socket.h>
4
#include <netdb.h>
5
#include <stdio.h>
6
#include<string.h>
7
8
int main()
9
{
10
11 char str[100];
15
17
bzero( &servaddr, sizeof(servaddr));
18
19
servaddr.sin_family = AF_INET;
20
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
21
servaddr.sin_port = htons(22000);
22
23
bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
24
25
listen(listen_fd, 10);
26
28
29 while(1)
30 {
31
33
read(comm_fd,str,100);
34
35
printf("Echoing back - %s",str);
36
37
38 write(comm_fd, str, strlen(str)+1);
39
40 }
}
41
42
43
Line by Line
1 int listen_fd, comm_fd;
Each server needs to “listen” for connections. The above function creates a socket with AF_INET (
IP Addressing ) and of type SOCK_STREAM. Data from all devices wishing to connect on this
socket will be redirected to listen_fd.
1 bzero( &servaddr, sizeof(servaddr));
1 servaddr.sin_family = AF_INET;
2 servaddr.sin_addr.s_addr = htons(INADDR_ANY);
3 servaddr.sin_port = htons(22000);
Prepare to listen for connections from address/port specified in sockaddr ( Any IP on port 22000 ).
1 listen(listen_fd, 10);
Start Listening for connections , keep at the most 10 connection requests waiting.If there are more
than 10 computers wanting to connect at a time, the 11th one fails to.
1 comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
Accept a connection from any device who is willing to connect, If there is no one who wants to
connect , wait. A file descriptor is returned. This can finally be used to communicate , whatever is
sent by the device accepted can be read from comm_fd, whatever is written to comm_fd is sent to
the other device.
1 bzero( str, 100);
2 read(comm_fd,str,100);
Clear str
read at most 100 bytes into str
display what it reads
send back str , (length of string + 1) so that is sent as well
Hello Sockets – Client
1 #include <sys/types.h>
2 #include <sys/socket.h>
3 #include <netdb.h>
#include <stdio.h>
4
#include<string.h>
5
6
int main(int argc,char **argv)
7
{
8
int sockfd,n;
9
char sendline[100];
10 char recvline[100];
12
13 sockfd=socket(AF_INET,SOCK_STREAM,0);
14 bzero(&servaddr,sizeof servaddr);
15
16 servaddr.sin_family=AF_INET;
17 servaddr.sin_port=htons(22000);
18
inet_pton(AF_INET,"127.0.0.1",&(servaddr.sin_addr));
19
20
connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
21
22
while(1)
23
{
24
bzero( sendline, 100);
25
bzero( recvline, 100);
26 fgets(sendline,100,stdin); /*stdin = 0 , for standard input */
27
28 write(sockfd,sendline,strlen(sendline)+1);
29 read(sockfd,recvline,100);
30 printf("%s",recvline);
}
31
32
}
33
34
35
Line by Line
I’ll only go over the new parts
1 inet_pton(AF_INET,"127.0.0.1",&(servaddr.sin_addr));
Set IP address in servaddr to “127.0.0.1” ( computers way of saying myself ) since our server is also
on the same machine . The address in servaddr needs to be in integer format , hence the
function inet_pton
1 connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
Connect to the device whose address and port number is specified in servaddr.
4 write(sockfd,sendline,strlen(sendline)+1);
5 read(sockfd,recvline,100);
printf("%s",recvline);
6
STAAAAHHPPPPPPPP !
7
STAAAAHHPPPPPPPP !
8
I hope this post is of some help to whoever reads it. I tried to keep it as simple as possible . Leave
Comments
/****************************************************************************
*/
/*** myping.c
***/
/***
***/
/*** Use the ICMP protocol to request "echo" from destination.
***/
/****************************************************************************
*/
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#define PACKETSIZE 64
struct packet
{
struct icmphdr hdr;
char msg[PACKETSIZE-sizeof(struct icmphdr)];
};
int pid=-1;
struct protoent *proto=NULL;
/*--------------------------------------------------------------------*/
/*--- checksum - standard 1s complement checksum ---*/
/*--------------------------------------------------------------------*/
unsigned short checksum(void *b, int len)
{ unsigned short *buf = b;
unsigned int sum=0;
unsigned short result;
/*--------------------------------------------------------------------*/
/*--- display - present echo info ---*/
/*--------------------------------------------------------------------*/
void display(void *buf, int bytes)
{ int i;
struct iphdr *ip = buf;
struct icmphdr *icmp = buf+ip->ihl*4;
printf("----------------\n");
for ( i = 0; i < bytes; i++ )
{
if ( !(i & 15) )
printf("\n
X: ", i);
printf("X ", ((unsigned char*)buf)[i]);
}
printf("\n");
printf("IPv%d: hdr-size=%d pkt-size=%d protocol=%d TTL=%d src=%s ",
ip->version, ip->ihl*4, ntohs(ip->tot_len), ip->protocol,
ip->ttl, inet_ntoa(ip->saddr));
printf("dst=%s\n", inet_ntoa(ip->daddr));
if ( icmp->un.echo.id == pid )
{
printf("ICMP: type[%d/%d] checksum[%d] id[%d] seq[%d]\n",
icmp->type, icmp->code, ntohs(icmp->checksum),
icmp->un.echo.id, icmp->un.echo.sequence);
}
}
/*--------------------------------------------------------------------*/
/*--- listener - separate process to listen for and collect messages--*/
/*--------------------------------------------------------------------*/
void listener(void)
{ int sd;
struct sockaddr_in addr;
unsigned char buf[1024];
bzero(buf, sizeof(buf));
bytes = recvfrom(sd, buf, sizeof(buf), 0, (struct
sockaddr*)&addr, &len);
if ( bytes > 0 )
display(buf, bytes);
else
perror("recvfrom");
}
exit(0);
}
/*--------------------------------------------------------------------*/
/*--- ping - Create message and send it. ---*/
/*--------------------------------------------------------------------*/
void ping(struct sockaddr_in *addr)
{ const int val=255;
int i, sd, cnt=1;
struct packet pckt;
struct sockaddr_in r_addr;
/*--------------------------------------------------------------------*/
/*--- main - look up host and start ping processes. ---*/
/*--------------------------------------------------------------------*/
int main(int count, char *strings[])
{ struct hostent *hname;
struct sockaddr_in addr;
if ( count != 2 )
{
printf("usage: %s <addr>\n", strings[0]);
exit(0);
}
if ( count > 1 )
{
pid = getpid();
proto = getprotobyname("ICMP");
hname = gethostbyname(strings[1]);
bzero(&addr, sizeof(addr));
addr.sin_family = hname->h_addrtype;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(long*)hname->h_addr;
if ( fork() == 0 )
listener();
else
ping(&addr);
wait(0);
}
else
printf("usage: myping <hostname>\n");
return 0;
}
#define DEFDATALEN 56
#define MAXIPLEN 60
#define MAXICMPLEN 76
if (nleft == 1) {
*(unsigned char *) (&ans) = *(unsigned char *) w;
sum += ans;
}
pingaddr.sin_family = AF_INET;
if (!(h = gethostbyname(host))) {
fprintf(stderr, "ping: unknown host %s\n", host);
exit(1);
}
memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
hostname = h->h_name;
if (c < 0 || c != sizeof(packet)) {
if (c < 0)
perror("ping: sendto");
fprintf(stderr, "ping: write incomplete\n");
exit(1);
}
signal(SIGALRM, noresp);
alarm(2); /* give the host 5000ms to
respond */
/* listen for replies */
while (1) {
struct sockaddr_in from;
size_t fromlen = sizeof(from);
int main ()
{
ping ("192.168.1.2");
}
CRC :ERoor Correction & Detection
1. #include <stdio.h>
2. #include <conio.h>
3. #include <string.h>
4. void main() {
5. int i,j,keylen,msglen;
6. char input[100], key[30],temp[30],quot[100],rem[30],key1[30];
7. clrscr();
8. printf("Enter Data: ");
9. gets(input);
10. printf("Enter Key: ");
11. gets(key);
12. keylen=strlen(key);
13. msglen=strlen(input);
14. strcpy(key1,key);
15. for (i=0;i<keylen-1;i++) {
16. input[msglen+i]='0';
17. }
18. for (i=0;i<keylen;i++)
19. temp[i]=input[i];
20. for (i=0;i<msglen;i++) {
21. quot[i]=temp[0];
22. if(quot[i]=='0')
23. for (j=0;j<keylen;j++)
24. key[j]='0'; else
25. for (j=0;j<keylen;j++)
26. key[j]=key1[j];
27. for (j=keylen-1;j>0;j--) {
28. if(temp[j]==key[j])
29. rem[j-1]='0'; else
30. rem[j-1]='1';
31. }
32. rem[keylen-1]=input[i+keylen];
33. strcpy(temp,rem);
34. }
35. strcpy(rem,temp);
36. printf("\nQuotient is ");
37. for (i=0;i<msglen;i++)
38. printf("%c",quot[i]);
39. printf("\nRemainder is ");
40. for (i=0;i<keylen-1;i++)
41. printf("%c",rem[i]);
42. printf("\nFinal data is: ");
43. for (i=0;i<msglen;i++)
44. printf("%c",input[i]);
45. for (i=0;i<keylen-1;i++)
46. printf("%c",rem[i]);
47. getch();
48. }
#!/usr/bin/awk
BEGIN {
bytes_recvd = 0;
throughput = 0;
interval = 1;
current_time_instance = 0;
nxt_time_instance = current_time_instance + interval;
}
{
action = $1;
time = $2;
from = $3;
to = $4;
type = $5;
pkt_size = $6;
flow_id = $8;
src = $9;
dst = $10;
sequence_n0 = $11;
pkt_id = $12;