0% found this document useful (0 votes)
89 views

Network Lab Manual 2019 Print

The document provides instructions on using common networking tools like TCPDUMP, NETSTAT, IFCONFIG, NSLOOKUP, PING and TRACEROUTE. It describes what each tool is used for and provides examples of commands to use TCPDUMP to capture and display network packets, NETSTAT to view active network connections and statistics, and IFCONFIG to view network interface configurations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Network Lab Manual 2019 Print

The document provides instructions on using common networking tools like TCPDUMP, NETSTAT, IFCONFIG, NSLOOKUP, PING and TRACEROUTE. It describes what each tool is used for and provides examples of commands to use TCPDUMP to capture and display network packets, NETSTAT to view active network connections and statistics, and IFCONFIG to view network interface configurations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

CS8581-Networks Lab Department of CSE 2019-2020

EX: NO: 1A USE COMMANDS LIKE TCPDUMP, NETSTAT, IFCONFIG, NSLOOKUP, PING AND
TRACEROUTE

AIM:

To use commands like TCPDUMP,NETSTAT,IFCONFIG,NSLOOKUP,PING and


TRACEROUTE.

DESCRIPTION:

TCPDUMP - tcpdump is a common packet analyzer that runs under the command line. It allows the
user to display TCP/IP and other packets being transmitted or received over a network to which the
computer is attached.

NETSTAT - In computing, netstat is a command-line network utility tool that displays network
connections for the Transmission Control Protocol, routing tables, and a number of network interface
and network protocol statistics.

IFCONFIG – ifconfig is a system administration utility in Unix-like operating systems for network
interface configuration. The utility is a command-line interface tool and is also used in the system
startup scripts of many operating systems.

NSLOOKUP - nslookup is a network administration command-line tool available in many computer


operating systems for querying the Domain Name System to obtain domain name or IP address
mapping, or other DNS records. The name "nslookup" means "name server lookup".

PING - Ping is a computer network administration software utility used to test the reachability of a
host on an Internet Protocol network.

TRACEROUTE - Traceroute helps you analyze the path packets take on a network, along with any
associated delays.

COMMANDS:

1.TCPDUMP

$ which tcpdump
/usr/sbin/tcpdump

[root@localhost ~]# which tcpdump


/usr/sbin/tcpdump

[root@localhost ~]# yum install -y tcpdump


Loaded plugins: aliases, changelog, fastestmirror, kabi, presto,
refresh-
: packagekit, security, tmprepo, verify, versionlock
Loading support for CentOS kernel ABI
Setting up Install Process
Loading mirror speeds from cached hostfile
* base: mirror.nbrc.ac.in
* extras: mirror.nbrc.ac.in
* updates: mirror.nbrc.ac.in

St.Joseph’s College of Engineering 1


CS8581-Networks Lab Department of CSE 2019-2020

Resolving Dependencies
--> Running transaction check
---> Package tcpdump.x86_64 14:4.0.0-5.20090921gitdf3cb4.2.el6 will
be updated
---> Package tcpdump.x86_64 14:4.0.0-11.20090921gitdf3cb4.2.el6 will
be an update
--> Finished Dependency Resolution

Dependencies Resolved
$ tcpdump -i any
[root@localhost ~]# tcpdump -i any

tcpdump: verbose output suppressed, use -v or -vv for full protocol


decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size
65535 bytes
05:49:36.881403 IP localhost.37155 > localhost.sunrpc: Flags [S],
seq 1122424847, win 65495, options [mss 65495,sackOK,TS val 742234
ecr 0,nop,wscale 7], length 0
05:49:36.881414 IP localhost.sunrpc > localhost.37155: Flags [S.],
seq 2202608496, ack 1122424848, win 65483, options [mss
65495,sackOK,TS val 742234 ecr 742234,nop,wscale 7], length 0
05:49:36.881423 IP localhost.37155 > localhost.sunrpc: Flags [.],
ack 1, win 512, options [nop,nop,TS val 742234 ecr 742234], length 0
05:49:36.881460 IP localhost.37155 > localhost.sunrpc: Flags [P.],
seq 1:61, ack 1, win 512, options [nop,nop,TS val 742235 ecr
742234], length 60
05:51:06.164582 ARP, Request who-has 10.10.113.29 tell 10.10.113.1,
171 packets captured
461 packets received by filter
180 packets dropped by kernel
$ tcpdump -i any -c 5
[root@localhost ~]# tcpdump -i any -c 5

tcpdump: verbose output suppressed, use -v or -vv for full protocol


decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size
65535 bytes
05:51:39.621246 IP localhost.52611 > localhost.sunrpc: Flags [S],
seq 2866910846, win 65495, options [mss 65495,sackOK,TS val 864974
ecr 0,nop,wscale 7], length 0
05:51:39.621256 IP localhost.sunrpc > localhost.52611: Flags [S.],
seq 2015432770, ack 2866910847, win 65483, options [mss
65495,sackOK,TS val 864974 ecr 864974,nop,wscale 7], length 0
05:51:39.621265 IP localhost.52611 > localhost.sunrpc: Flags [.],
ack 1, win 512, options [nop,nop,TS val 864974 ecr 864974], length 0
05:51:39.621297 IP localhost.52611 > localhost.sunrpc: Flags [P.],
5 packets captured
19 packets received by filter
0 packets dropped by kernel

St.Joseph’s College of Engineering 2


CS8581-Networks Lab Department of CSE 2019-2020

$ tcpdump -i any -c5 -nn


[root@localhost ~]# tcpdump -i any -c 5 –nn

tcpdump: verbose output suppressed, use -v or -vv for full protocol


decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size
65535 bytes
05:52:21.646487 IP 127.0.0.1.37860 > 127.0.0.1.111: Flags [S], seq
2129797790, win 65495, options [mss 65495,sackOK,TS val 906999 ecr
0,nop,wscale 7], length 0
05:52:21.646520 IP 127.0.0.1.111 > 127.0.0.1.37860: Flags [S.], seq
1878991630, ack 2129797791, win 65483, options [mss 65495,sackOK,TS
val 906999 ecr 906999,nop,wscale 7], length 0
05:52:21.646550 IP 127.0.0.1.37860 > 127.0.0.1.111: Flags [.], ack
61, win 512, options [nop,nop,TS val 907000 ecr 907000], length 0
5 packets captured
19 packets received by filter
0 packets dropped by kernel

2.NETSTAT

Listing all the LISTENING Ports of TCP and UDP connections

# netstat -a | more
[root@localhost ~]# netstat -a / more
s_socket
unix 3 [ ] STREAM CONNECTED 12283
unix 2 [ ] DGRAM 12279
unix 3 [ ] STREAM CONNECTED 12249
/var/run/dbus/system_bus_socket
unix 3 [ ] STREAM CONNECTED 12248
unix 3 [ ] STREAM CONNECTED 12242
unix 3 [ ] STREAM CONNECTED 12241
unix 2 [ ] DGRAM 12073
unix 3 [ ] STREAM CONNECTED 11593
unix 3 [ ] STREAM CONNECTED 11592
unix 3 [ ] STREAM CONNECTED 11583
unix 3 [ ] STREAM CONNECTED 11582
unix 3 [ ] DGRAM 8499
unix 3 [ ] DGRAM 8498

Listing TCP Ports connections

netstat –at

[root@localhost ~]# netstat –at

Active Internet connections (servers and established)


Proto Recv-Q Send-Q Local Address Foreign Address
State

St.Joseph’s College of Engineering 3


CS8581-Networks Lab Department of CSE 2019-2020

tcp 0 0 *:5800 *:*


LISTEN
tcp 0 0 *:vnc-server *:*
LISTEN
tcp 0 0 *:46959 *:*
LISTEN
tcp 0 0 *:sunrpc *:*
LISTEN
tcp 0 0 192.168.122.1:domain *:*
LISTEN
tcp 0 0 *:ssh *:*
LISTEN

Listing UDP Ports connections

netstat –au
[root@localhost ~]# netstat -au
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address
State
udp 0 0 *:dhcp-failover *:*
udp 0 0 *:imap *:*
udp 0 0 *:783 *:*
udp 0 0 *:58673 *:*
udp 0 0 192.168.122.1:domain *:*
udp 0 0 *:bootps *:*
udp 0 0 *:bootpc *:*

Listing all LISTENING Connections

[root@localhost ~]# netstat -l


Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address
State
tcp 0 0 *:5800 *:*
LISTEN
tcp 0 0 *:vnc-server *:*
LISTEN
tcp 0 0 *:46959 *:*
LISTEN
tcp 0 0 *:sunrpc *:*
LISTEN
Active UNIX domain sockets (only servers)
Proto RefCnt Flags Type State I-Node Path
unix 2 [ ACC ] STREAM LISTENING 33970 /tmp/orbit-
user/linc-13e0-0-c430743a7f55
unix 2 [ ACC ] STREAM LISTENING 28496 /tmp/.X11-
unix/X0
unix 2 [ ACC ] STREAM LISTENING 30994 @/tmp/.ICE-
unix/4618
unix 2 [ ACC ] STREAM LISTENING 28495 @/tmp/.X11-

St.Joseph’s College of Engineering 4


CS8581-Networks Lab Department of CSE 2019-2020

unix/X0
unix 2 [ ACC ] STREAM LISTENING 14671
/var/run/libvirt/libvirt-sock

Showing statistics of all protocols

# netstat –s

[root@localhost ~]# netstat -s


Ip:
3455 total packets received
1 with invalid addresses
0 forwarded
0 incoming packets discarded
3454 incoming packets delivered
3401 requests sent out
Icmp:
32 ICMP messages received
21 input ICMP message failed.
ICMP input histogram:
destination unreachable: 32
32 ICMP messages sent
0 ICMP messages failed
ICMP output histogram:
destination unreachable: 32
IcmpMsg:
InType3: 32
OutType3: 32
Tcp:
323 active connections openings
302 passive connection openings
14 failed connection attempts
0 connection resets received
0 connections established
3301 segments received
3231 segments send out
0 segments retransmited
0 bad segments received.
14 resets sent
Udp:
106 packets received
2 packets to unknown port received.
0 packet receive errors
142 packets sent
UdpLite:
TcpExt:
306 TCP sockets finished time wait in fast timer
4 delayed acks sent
533 packets header predicted
911 acknowledgments not containing data received
301 predicted acknowledgments
0 TCP data loss events

St.Joseph’s College of Engineering 5


CS8581-Networks Lab Department of CSE 2019-2020

IpExt:
InBcastPkts: 17
InOctets: 567702
OutOctets: 212164
InBcastOctets: 5328

3. IFCONFIG

1. Show Network Devices and configuration and all network setting

# ifconfig
[root@localhost ~]# ifconfig
eth0 Link encap:Ethernet HWaddr A0:48:1C:A4:1E:0C
inet addr:10.10.113.79 Bcast:10.10.113.255
Mask:255.255.255.0
inet6 addr: fe80::a248:1cff:fea4:1e0c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1264 errors:0 dropped:0 overruns:0 frame:0
TX packets:300 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:433958 (423.7 KiB) TX bytes:18540 (18.1 KiB)

lo Link encap:Local Loopback


inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:3142 errors:0 dropped:0 overruns:0 frame:0
TX packets:3142 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:198896 (194.2 KiB) TX bytes:198896 (194.2 KiB)

virbr0 Link encap:Ethernet HWaddr 52:54:00:7F:52:22


inet addr:192.168.122.1 Bcast:192.168.122.255
Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

2. To Display the Information of all network interface

# ifconfig -a
eth0 Link encap:Ethernet HWaddr A0:48:1C:A4:1E:0C
inet addr:10.10.113.79 Bcast:10.10.113.255
Mask:255.255.255.0
inet6 addr: fe80::a248:1cff:fea4:1e0c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1293 errors:0 dropped:0 overruns:0 frame:0
TX packets:300 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000

St.Joseph’s College of Engineering 6


CS8581-Networks Lab Department of CSE 2019-2020

RX bytes:435973 (425.7 KiB) TX bytes:18540 (18.1 KiB)

lo Link encap:Local Loopback


inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:3142 errors:0 dropped:0 overruns:0 frame:0
TX packets:3142 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:198896 (194.2 KiB) TX bytes:198896 (194.2 KiB)

virbr0 Link encap:Ethernet HWaddr 52:54:00:7F:52:22


inet addr:192.168.122.1 Bcast:192.168.122.255
Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

virbr0-nic Link encap:Ethernet HWaddr 52:54:00:7F:52:22


BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:500
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

4. NSLOOKUP

1. To find the IP address of a host, simply type the hostname:

# nslookup google.com

Server: 8.8.8.8
Address: 8.8.8.8#53

Non-authoritative answer:
Name: google.com
Address: 216.58.196.174

5.PING
1. Ping the host to see if its alive

$ ping google.com
[root@localhost ~]# ping google.com
PING google.com (172.217.163.46) 56(84) bytes of data.
64 bytes from maa05s01-in-f14.1e100.net (172.217.163.46): icmp_seq=1
ttl=57 time=2.41 ms
64 bytes from maa05s01-in-f14.1e100.net (172.217.163.46): icmp_seq=2
ttl=57 time=2.00 ms
64 bytes from maa05s01-in-f14.1e100.net (172.217.163.46): icmp_seq=3

St.Joseph’s College of Engineering 7


CS8581-Networks Lab Department of CSE 2019-2020

ttl=57 time=2.08 ms
64 bytes from maa05s01-in-f14.1e100.net (172.217.163.46): icmp_seq=4
ttl=57 time=3.75 ms
64 bytes from maa05s01-in-f14.1e100.net (172.217.163.46): icmp_seq=5
ttl=57 time=2.22 ms
64 bytes from maa05s01-in-f14.1e100.net (172.217.163.46): icmp_seq=6
ttl=57 time=1.93 ms
64 bytes from maa05s01-in-f14.1e100.net (172.217.163.46): icmp_seq=7
ttl=57 time=2.05 ms

[root@localhost ~]# ping -c 4 google.com


PING google.com (172.217.26.174) 56(84) bytes of data.
64 bytes from maa03s22-in-f14.1e100.net (172.217.26.174): icmp_seq=1
ttl=56 time=16.7 ms
64 bytes from maa03s22-in-f14.1e100.net (172.217.26.174): icmp_seq=2
ttl=56 time=8.27 ms
64 bytes from maa03s22-in-f14.1e100.net (172.217.26.174): icmp_seq=3
ttl=56 time=9.17 ms
64 bytes from maa03s22-in-f14.1e100.net (172.217.26.174): icmp_seq=4
ttl=56 time=13.6 ms
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3018ms
rtt min/avg/max/mdev = 8.270/11.964/16.794/3.447 ms

Send N packets and stop

6.TRACE ROUTE

$ traceroute google.com
traceroute to google.com (172.217.163.46), 30 hops max, 60 byte
packets
1 * * *
2 192.168.1.2 (192.168.1.2) 0.229 ms 0.447 ms 0.422 ms
3 220.225.121.206 (220.225.121.206) 1.497 ms 1.156 ms PTPL-
AS56272-REV-137.108.254.43-CHN.PULSE.IN (43.254.108.137) 116.834 ms
4 182.79.198.6 (182.79.198.6) 10.556 ms * *
5 * as15169.maa.extreme-ix.net (45.120.251.135) 121.042 ms
72.14.211.198 (72.14.211.198) 3.526 ms
6 * * *
7 216.239.42.215 (216.239.42.215) 120.869 ms 3.552 ms
74.125.51.2 (74.125.51.2) 2.466 ms
8 74.125.242.129 (74.125.242.129) 3.833 ms maa05s01-in-
f14.1e100.net (172.217.163.46) 117.253 ms 3.565 ms

Result:

Thus the commands TCPdump, Netsatat,Ping and Traceroute has been implemented successfully.

St.Joseph’s College of Engineering 8


CS8581-Networks Lab Department of CSE 2019-2020

Ex.No.1B CAPTURE PING AND TRACE ROUTE PDUs USING NETWORK

PROTOCOL ANALYZER

DESCRIPTION

Wireshark is a software protocol analyzer, or "packet sniffer" application, used for network
troubleshooting, analysis, software and protocol development, and education. t has a rich and
powerful feature set and runs on most computing platforms including Windows, OS X, Linux, and
UNIX. Network professionals, security experts, developers, and educators around the world use it
regularly. It is freely available as open source, and is released under the GNU General Public License
version 2.

Steps:
1. Open Wireshark application
2. To start PDU capture, go to Capture on the Menu bar and select Options. The Capture
Options dialog box provides a range of settings and filters which determines which and how
much data traffic is captured.
3. Ensure that Wireshark is set to monitor the correct interface.
4. Click the Start button on the Wireshark: Capture Options window. This would show a
Capture Information Dialog, and the Main Display Window would then be divided into
different panes similar to the window
5. When the Stop button is clicked, the capture process is terminated, and the main screen is
displayed. This Main Display Window of Wireshark has three panes. a. Packet List pane
b.Packet Details Pane c.Packet bytes pane.

St.Joseph’s College of Engineering 9


CS8581-Networks Lab Department of CSE 2019-2020

Result:
Thus the commands and caputing of Ping and Traceroute completed successfully.

St.Joseph’s College of Engineering 10


CS8581-Networks Lab Department of CSE 2019-2020

EX:NO:2 HTTP web client program to download a web page using TCP sockets

AIM:
To write a HTTP web client program to download a web page using TCP sockets.

ALGORITHM :

Steps:
1. Create a URL object and pass url as string to download the webpage.
URL example = new URL(pass url of webpage you want to download)
2. Create Buffered Reader object and pass openStream(). Method of URL in Input Stream object.
3. Create a string object to read each line one by one from stream.
4. Write each line in html file where webpage will be downloaded.
5. Close all objects.
6. Catch exceptions if url failed to download.

PROGRAM

import java.io.*;
import java.net.*;

public class SocketHTTPClient {


public static void main(String[] args) {

String hostName = "www.google.com";


int portNumber = 80;

try {
Socket socket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out.println("GET / HTTP/1.1\nHost: www.martinbroadhurst.com
\n\n");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}

St.Joseph’s College of Engineering 11


CS8581-Networks Lab Department of CSE 2019-2020

Output:

[user@localhost Desktop]$ javac SocketHTTPClient.java


[user@localhost Desktop]$ java SocketHTTPClient
^[[AHTTP/1.1 200 OK
Date: Thu, 29 Aug 2019 05:46:13 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.3.10-1ubuntu3.25
X-Pingback: http://www.martinbroadhurst.com/xmlrpc.php
Link: <http://www.martinbroadhurst.com/wp-json/>; rel="https://api.w.org/"
Link: <http://www.martinbroadhurst.com/>; rel=shortlink
Vary: Accept-Encoding
Keep-Alive: timeout=5, max=100
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
Via: HTTP/1.1 forward.http.proxy:3128
Connection: keep-alive

2118
<!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" lang="en-US">
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" lang="en-US">
<![endif]-->
<!--[if !(IE 7) & !(IE 8)]><!-->
<html lang="en-US">
<!--<![endif]-->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Martin Broadhurst</title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback"
href="http://www.martinbroadhurst.com/xmlrpc.php">
<!--[if lt IE 9]>
<script src="http://www.martinbroadhurst.com/wp-
content/themes/twentyfourteen/js/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" title="Martin
Broadhurst &raquo; Feed" href="http://www.martinbroadhurst.com/feed" />
<link rel="alternate" type="application/rss+xml" title="Martin Broadhurst
&raquo; Comments Feed"
href="http://www.martinbroadhurst.com/comments/feed" />
<link rel="alternate" type="application/rss+xml" title="Martin Broadhurst
&raquo; Martin Broadhurst Comments Feed"
href="http://www.martinbroadhurst.com/sample-page/feed" />
<script type="text/javascript">
window._wpemojiSettings =
{"baseUrl":"https:\/\/round-lake.dustinice.workers.dev:443\/https\/s.w.org\/images\/core\/emoji\/72x72\/","ext":".png",
"source":{"concatemoji":"https:\/\/round-lake.dustinice.workers.dev:443\/http\/www.martinbroadhurst.com\/wp-
includes\/js\/wp-emoji-release.min.js?ver=4.5"}};
!function(a,b,c){function d(a){var
c,d,e,f=b.createElement("canvas"),g=f.getContext&&f.getContext("2d"),h=Str
ing.fromCharCode;if(!g||!g.fillText)return!1;switch(g.textBaseline="top",g
.font="600 32px Arial",a){case"flag":return

St.Joseph’s College of Engineering 12


CS8581-Networks Lab Department of CSE 2019-2020

g.fillText(h(55356,56806,55356,56826),0,0),f.toDataURL().length>3e3;case"d
iversity":return
g.fillText(h(55356,57221),0,0),c=g.getImageData(16,16,1,1).data,g.fillText
(h(55356,57221,55356,57343),0,0),c=g.getImageData(16,16,1,1).data,e=c[0]+"
,"+c[1]+","+c[2]+","+c[3],d!==e;case"simple":return
g.fillText(h(55357,56835),0,0),0!==g.getImageData(16,16,1,1).data[0];case"
unicode8":return
g.fillText(h(55356,57135),0,0),0!==g.getImageData(16,16,1,1).data[0]}retur
n!1}function e(a){var
c=b.createElement("script");c.src=a,c.type="text/javascript",b.getElements
ByTagName("head")[0].appendChild(c)}var
f,g,h,i;for(i=Array("simple","flag","unicode8","diversity"),c.supports={ev
erything:!0,everythingExceptFlag:!0},h=0;h<i.length;h++)c.supports[i[h]]=d
(i[h]),c.supports.everything=c.supports.everything&&c.supports[i[h]],"flag
"!==i[h]&&(c.supports.everythingExceptFlag=c.supports.everythingExceptFlag
&&c.supports[i[h]]);c.supports.everythingExceptFlag=c.supports.everythingE
xceptFlag&&!c.supports.flag,c.DOMReady=!1,c.readyCallback=function(){c.DOM
Ready=!0},c.supports.everything||(g=function(){c.readyCallback()},b.addEve
ntListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener
("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechang
e",function(){"complete"===b.readyState&&c.readyCallback()})),f=c.source||
{},f.concatemoji?e(f.concatemoji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.
wpemoji)))}(window,document,window._wpemojiSettings);
</script>
<style type="text/css">
img.wp-smiley,
img.emoji {
display: inline !important;
border: none !important;
box-shadow: none !important;
height: 1em !important;
width: 1em !important;
margin: 0 .07em !important;
vertical-align: -0.1em !important;
background: none !important;
padding: 0 !important;
}
</style>
<link rel='stylesheet' id='twentyfourteen-lato-css'
href='https://fonts.googleapis.com/css?family=Lato%3A300%2C400%2C700%2C900
%2C300italic%2C400italic%2C700italic&#038;subset=latin%2Clatin-ext'
type='text/css' media='all' />
<link rel='stylesheet' id='genericons-css'
href='http://www.martinbroadhurst.com/wp-
content/themes/twentyfourteen/genericons/genericons.css?ver=3.0.3'
type='text/css' media='all' />
<link rel='stylesheet' id='twentyfourteen-style-css'
href='http://www.martinbroadhurst.com/wp-
content/themes/twentyfourteen/style.css?ver=4.5' type='text/css'
media='all' />
<!--[if lt IE 9]>
<link rel='stylesheet' id='twentyfourteen-ie-css'
href='http://www.martinbroadhurst.com/wp-
content/themes/twentyfourteen/css/ie.css?ver=20131205' type='text/css'
media='all' />
<![endif]-->
<script type='text/javascript' src='http://www.martinbroadhurst.com/wp-

St.Joseph’s College of Engineering 13


CS8581-Networks Lab Department of CSE 2019-2020

includes/js/jquery/jquery.js?ver=1.12.3'></script>
<script type='text/javascript' src='http://www.martinbroadhurst.com/wp-
includes/js/jquery/jquery-migrate.min.js?ver=1.4.0'></script>
<link rel='https://api.w.org/' href='http://www.martinbroadhurst.com/wp-
json/' />
<link rel="EditURI" type="application/rsd+xml" title="RSD"
href="http://www.martinbroadhurst.com/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml"
href="http://www.martinbroadhurst.com/wp-includes/wlwmanifest.xml" />
<meta name="generator" content="WordPress 4.5" />
<link rel="canonical" href="http://www.martinbroadhurst.com/" />
<link rel='shortlink' href='http://www.martinbroadhurst.com/' />
<link rel="alternate" type="application/json+oembed"
href="http://www.martinbroadhurst.com/wp-
json/oembed/1.0/embed?url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttp%2Fwww.martinbroadhurst.com%2F" />
<link rel="alternate" type="text/xml+oembed"
href="http://www.martinbroadhurst.com/wp-
json/oembed/1.0/embed?url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttp%2Fwww.martinbroadhurst.com%2F&#038;fo
rmat=xml" />
<style type="text/css">.recentcomments a{display:inline
!important;padding:0 !important;margin:0 !important;}</style>
<style type="text/css" id="syntaxhighlighteranchor"></style>
</head>

<body class="home singular page page-id-2 page-template-default masthead-


fixed full-width grid">
<div id="page" class="hfeed site">

<header id="masthead" class="site-header" role="banner">


<div class="header-main">
<h1 class="site-title"><a
href="http://www.martinbroadhurst.com/" rel="home">Martin
Broadhurst</a></h1>

Result:
Thus a HTTP web client program to download a web page using TCP sockets been done and
executed successfully.

St.Joseph’s College of Engineering 14


CS8581-Networks Lab Department of CSE 2019-2020

EX:NO:3A Applications of TCP Sockets – Echo Client and Echo Server

AIM:
To write a java program for the application of TCP sockets – Echo client and Echo Server.

ALGORITHM:
1. Start the program
2. Establish a socket connection, The java.net.Socket class represents a Socket
3. Input streams and output streams are used to communicate over a socket connection for both
input and output the data.
4. Server makes a new Socket to communicate with the client.
5. The accept() method blocks, until a client connects to the server.
6. A ServerSocket which waits for the client requests (when a client makes a new
Socket())
7. getOutputStream() method is used to send the output through the socket.
8. Close the connection by closing the socket and the input stream.

PROGRAM:
SERVER PROGRAM:

import java.net.*;
import java.io.*;
public class Server
{
public static void main( String args[]) throws Exception
{
ServerSocket srs = new ServerSocket(1234);
System.out.println("Server is running...");
Socket ss=srs.accept();
System.out.println("connection establised");
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new
InputStreamReader(ss.getInputStream()));
DataOutputStream dos = new DataOutputStream(ss.getOutputStream());

while(true)
{
//System.out.println("server repeat as long as client not send
null");
String s2,s3;
while((s2=br.readLine())!=null)
{
System.out.println("Client said : "+s2);
System.out.println("Enter text ");
s3 = kb.readLine();
//System.out.println("Answer send to client machine");
dos.writeBytes(s3+"\n");
}
System.out.println("Terminated..");
ss.close();
srs.close();

St.Joseph’s College of Engineering 15


CS8581-Networks Lab Department of CSE 2019-2020

dos.close();
kb.close();
System.exit(0);
}
}
}

CLIENT PROGRAM:

import java.net.*;
import java.io.*;
public class Client
{
public static void main( String args[]) throws Exception
{
Socket cs = new Socket("localhost",1234);
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
DataOutputStream dos = new
DataOutputStream(cs.getOutputStream());

System.out.println(" Enter text..");


System.out.println(" if client 'quit' type exit");

String s1,s4=null;
while(!(s1=kb.readLine()).equals("exit"))
{
//System.out.println(" data send to server machine");
dos.writeBytes(s1+"\n");

s4 = br.readLine();
//System.out.println(" data receive from server
machine");
System.out.println("Server said : "+s4);
System.out.println("Enter text ");

}
System.out.println("Terminated..");
cs.close();
dos.close();
kb.close();
}
}

St.Joseph’s College of Engineering 16


CS8581-Networks Lab Department of CSE 2019-2020

Output:

[user@localhost Desktop]$ javac Server.java


[user@localhost Desktop]$ java Server
Server is running...
connection establised
server send echo to client
server send echo to client

[user@localhost Desktop]$ javac Client2.java


[user@localhost Desktop]$ java Client2
Enter text..
if client 'quit' type exit
hello
Server said : hello
Enter text
how are you
Server said : how are you

Result:

Thus the simulation program for Echoserver Echoclient is executed successfully.

St.Joseph’s College of Engineering 17


CS8581-Networks Lab Department of CSE 2019-2020

EX:NO: 3B Applications of TCP Sockets – CHAT

AIM:
To write a java program for the application of TCP sockets like CHAT.

ALGORITHM:
1. In any Client/Server Application, run the server before the client, because the server keeps waiting for
the client to be connected.
2. Server keeps listening for the client on an assigned IP & Port
3. For establishing connection client must know the IP & Port of the server.
4. When we start Client Application, It creates a connection to the server.
5. After the Successful connection Client & Server Applications can send & receive messages

CLIENT PROGRAM:
import java.net.*;
import java.io.*;
public class Client1
{
public static void main( String args[]) throws Exception
{
Socket cs = new Socket("localhost",1234);
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
DataOutputStream dos = new DataOutputStream(cs.getOutputStream());

System.out.println(" Enter text..");


System.out.println(" if client 'quit' type exit");

String s1,s4=null;
while(!(s1=kb.readLine()).equals("exit"))
{
//System.out.println(" data send to server machine");
dos.writeBytes(s1+"\n");

s4 = br.readLine();
//System.out.println(" data receive from server machine");
System.out.println("Server said : "+s4);
System.out.println("Enter text ");

}
System.out.println("Terminated..");
cs.close();
dos.close();
kb.close();
}
}

St.Joseph’s College of Engineering 18


CS8581-Networks Lab Department of CSE 2019-2020

SERVER PROGRAM:
import java.net.*;
import java.io.*;
public class Server1
{
public static void main( String args[]) throws Exception
{
ServerSocket srs = new ServerSocket(1234);
System.out.println("Server is running...");
Socket ss=srs.accept();
System.out.println("connection establised");
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new
InputStreamReader(ss.getInputStream()));
DataOutputStream dos = new DataOutputStream(ss.getOutputStream());

while(true)
{
//System.out.println("server repeat as long as client not send null");
String s2,s3;
while((s2=br.readLine())!=null)
{
System.out.println("Client said : "+s2);
System.out.println("Enter text ");
s3 = kb.readLine();
//System.out.println("Answer send to client machine");
dos.writeBytes(s3+"\n");
}
System.out.println("Terminated..");
ss.close();
srs.close();
dos.close();
kb.close();
System.exit(0);
}
}
}

Output:

Server

[user@localhost sample]$ javac Server.java


[user@localhost sample]$ java Server1
Server is running...
connection establised
Client said : hi
Enter text
how are u?
Client said : fine.

St.Joseph’s College of Engineering 19


CS8581-Networks Lab Department of CSE 2019-2020

Enter text
ok

Client
[user@localhost sample]$ javac Client1.java
[user@localhost sample]$ java Client1
Enter text..
if client 'quit' type exit
hi
Server said : how are u?
Enter text
fine.
Server said : ok

Result:

Thus the program for TCP CHAT is implemented Sucessfully.

St.Joseph’s College of Engineering 20


CS8581-Networks Lab Department of CSE 2019-2020

EX:NO: 3C Applications of TCP Sockets – FILE TRANSFER

AIM:
To write a java program for the application of TCP sockets like FILE TRANSFER.

ALGORITHM:
1. Start the program
2. Initialize the sockets.
3. Accept the client connection using the socket descriptor and the server address
4. Using File reader and buffered reader read the file which is created in the client program.
5. In the client program the file is created and data is entered.
6. Open the file and read the line line by line and write bytes.
7. Display the content from the file on the console.
8. Close the connection
9. Stop the program

SERVER PROGRAM
import java.io.*;
import java.net.*;
import java.util.*;
class Serverfile
{ public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(139);
while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=b.readLine())!=null)
{ System.out.println(s);
dout.writeBytes(s+'\n');
}
f.close();
dout.writeBytes("-1\n");
} }
catch(Exception e)
{ System.out.println(e);}
}}

CLIENT PROGRAM
import java.io.*;
import java.net.*;
import java.util.*;
class Clientfile
{ public static void main(String args[])

St.Joseph’s College of Engineering 21


CS8581-Networks Lab Department of CSE 2019-2020

{
Try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the file name:");
String str=in.readLine();
dout.writeBytes(str+'\n');
System.out.println("Enter the new file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2);
char buffer[];
while(true)
{ str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
}
f.close();
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}}}
OUTPUT:
SERVER
[user@localhost Desktop]$ javac Serverfile.java
[user@localhost Desktop]$ java Serverfile
Hii
Hello
Welcome
This is my file
CLIENT
[user@localhost Desktop]$ javac Clientfile.java
[user@localhost Desktop]$ java Clientfile
Enter the filename:
myfile.txt

Result: The simulation program to implement TCP file transfer is implemented successfully.

St.Joseph’s College of Engineering 22


CS8581-Networks Lab Department of CSE 2019-2020

EX: NO: 4 Simulation of DNS using UDP Sockets

AIM:
To implement a DNS server and client in java using UDP sockets.

ALGORITHM:
Server
1. Create an array of hosts and its ip address in another array
2. Create a datagram socket and bind it to a port
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Create a datagram packet and send ip address to client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop
Client
1. Create a datagram socket
2. Get domain name from user
3. Create a datagram packet and send domain name to the server
4. Create a datagram packet to receive server message
5. Read server's response
6. If ip address then display it else display "Domain does not exist"
7. Close the client socket
8. Stop
.
PROGRAM
// UDP DNS Server -- udpdnsserver.java
import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str))
return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com",
"facebook.com"};
String[] ip = {"68.180.206.184",
"209.85.148.19","80.168.92.140","69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");

St.Joseph’s College of Engineering 23


CS8581-Networks Lab Department of CSE 2019-2020

while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new
DatagramPacket(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
}

//UDP DNS Client -- udpdnsclient.java


import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length,
ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new
DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close(); }}

SERVER:

St.Joseph’s College of Engineering 24


CS8581-Networks Lab Department of CSE 2019-2020

[user@localhost Desktop]$ javac udpdnsserver.java


[user@localhost Desktop]$ java udpdnsserver
Press Ctrl+c to quit
Request for hostyahoo.com

CLIENT:
[user@localhost Desktop]$ javac udpdnsclient.java
[user@localhost Desktop]$ java udpdnsclient
Enter the hostname:
yahoo.com
IPAddress:68.180.206.184

Result:
Thus the DNS simulation program using UDP Sockets is implemented successfully.

St.Joseph’s College of Engineering 25


CS8581-Networks Lab Department of CSE 2019-2020

EX: NO: 5 Simulation of ARP and RARP Protocols

Aim:

To write a java program for simulating arp/rarp protocols

Algorithm:
server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Send servers date and time to the client.
4. Read clients IP address sent by the client.
5. Display the client details.
6. Repeat steps 2-5 until the server is terminated.
7. Close all streams.
8. Close the server socket.
9. Stop.
Client
1. Create a client socket and connect it to the server‟ s port number.
2. Retrieve its own IP address using built-in function.
3. Send its address to the server.
4. Display the date & time sent by the server.
5. Close the input and output streams.
6. Close the client socket.
7. Stop.

Program
Program for Address Resolutuion Protocol (ARP) using TCP

Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
Try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is: "+str);
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}

St.Joseph’s College of Engineering 26


CS8581-Networks Lab Department of CSE 2019-2020

}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(139);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}

}
catch(Exception e)
{
System.out.println(e);
}
}

Program for Reverse Address Resolutuion Protocol (RARP) using UDP

Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp12
{
public static void main(String args[])
{
try
{
DatagramSocket client=new DatagramSocket();
InetAddress addr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Physical address (MAC):");

St.Joseph’s College of Engineering 27


CS8581-Networks Lab Department of CSE 2019-2020

}
String str=in.readLine();
sendbyte=str.getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new String(receiver.getData());
System.out.println("The Logical Address is(IP): "+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp12
{
public static void main(String args[])
{
try
{
DatagramSocket server=new DatagramSocket(1309);
while(true)
{
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
//System.out.println(s); String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(mac[i]))
{
sendbyte=ip[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
break;
}
}
catch(Exception e)
{

St.Joseph’s College of Engineering 28


CS8581-Networks Lab Department of CSE 2019-2020

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

ARP:
SERVER:
[user@localhost Desktop]$ javac Serverarp.java
[user@localhost Desktop]$ java Serverarp

CLIENT:
[user@localhost Desktop]$ javac Clientarp.java
[user@localhost Desktop]$ java Clientarp
Enter the logical address(IP):
165.165.80.80
The Physical Address is:6A:08:AA:C2

RARP:
SERVER:
[user@localhost Desktop]$ javac Serverrarp12.java
[user@localhost Desktop]$ java Serverrarp12

CLIENT:
[user@localhost Desktop]$ javac Clientrarp12.java
[user@localhost Desktop]$ java Clientrarp12
Enter the physical address(MAC):
6A:08:AA:C2
The Logical Address is (IP):165.165.80.80

Result:
Thus the simulation program for ARP/RARP protocol is implemented successfully.

St.Joseph’s College of Engineering 29


CS8581-Networks Lab Department of CSE 2019-2020

Ex:No: 6A Study of Network simulator (NS)

AIM:

To study of ns2 in detail.

DESCRIPTION:

ns is an object oriented simulator, written in C++, with an OTcl interpreter as a frontend. The
simulator supports a class hierarchy in C++ (also called the compiled hierarchy in this document),
and a similar class hierarchy within the OTcl interpreter (also called the interpreted hierarchy in this
document). The two hierarchies are closely related to each other; from the user’s perspective, there is
a one-to-one correspondence between a class in the interpreted hierarchy and one in the compiled
hierarchy. The root of this hierarchy is the class TclObject. Users create new simulator objects through
the interpreter; these objects are instantiated within the interpreter, and are closely mirrored by a
corresponding object in the compiled hierarchy. The interpreted class hierarchy is automatically
established through methods defined in the class TclClass. User instantiated objects are mirrored
through methods defined in the class TclObject. There are other hierarchies in the C++ code and OTcl
scripts; these other hierarchies are not mirrored in the manner of TclObject.

CONCEPT OVERVIEW:
ns uses two languages because simulator has two different kinds of things it needs to do. On
one hand,detailed simulations of protocols requires a systems programming language which can
efficiently manipulate bytes, packet headers, and implement algorithms that run over large data sets.
For these tasks run-time speed is important and turn-around time (run simulation, find bug, fix bug,
recompile, re-run) is less important. On the other hand, a large part of network research involves
slightly varying parameters or configurations, or quickly exploringa number of scenarios. In these
cases, iteration time (change the model and re-run) is more important. Since configuration runs once
(at the beginning of the simulation), run-time of this part of the task is less important. ns meets both
of these needs with two languages, C++ and OTcl. C++ is fast to run but slower to change, making it
suitable for detailed protocol implementation. OTcl runs much slower but can be changed very
quickly (and interactively), making it ideal for simulation configuration. ns (via tclcl) provides glue to
make objects and variables appear on both langauges.

SIMULATOR INITIALIZATION:
When a new simulation object is created in tcl, the initialization procedure performs the
following operations:
• initialize the packet format (calls create_packetformat)
• create a scheduler (defaults to a calendar scheduler)
• create a “null agent” (a discard sink used in various places)

SCHEDULERS AND EVENTS:


The simulator is an event-driven simulator. There are presently four schedulers available in
the simulator, each of which is implemented using a different data structure: a simple linked-list,
heap, calendar queue (default), and a special type call called “real-time”. Each of these are described
below. The scheduler runs by selecting the next earliest event, executing it to completion, and
returning to execute the next event.Unit of time used by scheduler is seconds. Presently, the
simulator is single-threaded, and only one event in execution at any given time. If more than one
event are scheduled to execute at the same time, their execution is performed on the first scheduled –
first dispatched manner. Simultaneous events are not reordered anymore by schedulers (as it was in
earlier versions) and all schedulers should yeild the same order of dispatching
given the same input.

St.Joseph’s College of Engineering 30


CS8581-Networks Lab Department of CSE 2019-2020

NODE BASICS:
The basic primitive for creating a node is
set ns [new Simulator]
$ns node
The instance procedure node constructs a node out of more simple classifier objects (Section 5.4). The
Node itself is a standalone class in OTcl. However, most of the components of the node are
themselves TclObjects. The typical structure of a (unicast) node is as shown in Figure 5.1. This simple
structure consists of two TclObjects: an address classifer (classifer_) and a port classifier (dmux_). The
function of these classifiers is to distribute incoming packets to the correct agent or outgoing link.
All nodes contain at least the following components:
 an address or id_, monotonically increasing by 1 (from initial value 0) across the simulation
namespace as nodes are created,
 a list of neighbors (neighbor_),

BASIC COMMANDS IN NS2:

set ns [new Simulator]: generates an NS simulator object instance, and assigns it to variable ns.The
"Simulator" object has member functions that do the following:

 Create compound objects such as nodes and links (described later)


 Connect network component objects created (ex. attach-agent)
 Set network component parameters (mostly for compound objects)
 Create connections between agents (ex. make connection between a "tcp" and "sink")
 Specify NAM display options
 Most of member functions are for simulation setup (referred to as plumbing functions in the
overview section) and scheduling, however some of them are for the NAM display.
 The "Simulator" object member function implementations are located in the "ns-2/tcl/lib/ns-
lib.tcl" file.

 $ns color fid color: is to set color of the packets for a flow specified by the flow id (fid). This
member function of "Simulator" object is for the NAM display, and has no effect on the actual
simulation.
 $ns namtrace-all file-descriptor: This member function tells the simulator to record simulation
traces in NAM input format. It also gives the file name that the trace will be written to later by
the command $ns flush-trace. Similarly, the member function trace-all is for recording the
simulation trace in a general format.
 proc finish {}: is called after this simulation is over by the command $ns at 5.0 "finish". In this
function, post-simulation processes are specified.
 set n0 [$ns node]: The member function node creates a node. A node in NS is compound
object made of address and port classifiers (described in a later section). Users can create a
node by separately creating an address and a port classifier objects and connecting them
together. However, this member function of Simulator object makes the job easier. To see how
a node is created, look at the files: "ns-2/tcl/libs/ns-lib.tcl"andns-2/tcl/libs/ns-node.tcl".

St.Joseph’s College of Engineering 31


CS8581-Networks Lab Department of CSE 2019-2020

 $ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links of specified
bandwidth and delay, and connects the two specified nodes. In NS, the output queue of a
node is implemented as a part of a link, therefore users should specify the queue-type when
creating links. In the above simulation script, DropTail queue is used. If the reader wants to
use a RED queue, simply replace the word DropTail with RED. The NS implementation of a
link is shown in a later section. Like a node, a link is a compound object, and users can create
its sub-objects and connect them and the nodes. Link source codes can be found in "ns-
2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl" files. One thing to note is that you can
insert error modules in a link component to simulate a lossy link (actually users can make and
insert any network objects). Refer to the NS documentation to find out how to do this.

 $ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex links that
connect node1 and node2 to the number specified. At this point, the authors do not know how
many of these kinds of member functions of Simulator objects are available and what they are.
Please take a look at "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl", or NS.
 $ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAM display. To
see the effects of these lines, users can comment these lines out and try the simulation.
 Now that the basic network setup is done, the next thing to do is to setup traffic agents such
as TCP and UDP, traffic sources such as FTP and CBR, and attach them to nodes and agents
respectively.
 set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general, users can
create any agent or traffic sources in this way. Agents and traffic sources are in fact basic
objects (not compound objects), mostly implemented in C++ and linked to OTcl. Therefore,
there are no specific Simulator object member functions that create these object instances. To
create agents or traffic sources, a user should know the class names these objects (Agent/TCP,
Agnet/TCPSink, Application/FTP and so on). This information can be found in the NS
documentation or partly in this documentation. But one shortcut is to look at the
"ns2/tcl/libs/ns-default.tcl" file. This file contains the default configurable parameter value
settings for available network objects. Therefore, it works as a good indicator of what kind of
network objects are available in NS and what are the configurable parameters.

 $ns attach-agent node agent: The attach-agent member function attaches an agent object created
to a node object. Actually, what this function does is call the attach member function of
specified node, which attaches the given agent to itself. Therefore, a user can do the same
thing by, for example, $n0 attach $tcp. Similarly, each agent object has a member function .
 $ns connect agent1 agent2: After two agents that will communicate with each other are created,
the next thing is to establish a logical network connection between them. This line establishes
a network connection by setting the destination address to each others' network and port
address pair.
 Assuming that all the network configuration is done, the next thing to do is write a simulation
scenario (i.e. simulation scheduling). The Simulator object has many scheduling member
functions. However, the one that is mostly used is the following:
 $ns at time "string": This member function of a Simulator object makes the scheduler
(scheduler_ is the variable that points the scheduler object created by [new Scheduler]
command at the beginning of the script) to schedule the execution of the specified string at
given simulation time. For example, $ns at 0.1 "$cbr start" will make the scheduler call a start

St.Joseph’s College of Engineering 32


CS8581-Networks Lab Department of CSE 2019-2020

member function of the CBR traffic source object, which starts the CBR to transmit data. In
NS, usually a traffic source does not transmit actual data, but it notifies the underlying agent
that it has some amount of data to transmit, and the agent, just knowing how much of the
data to transfer, creates packets and sends them.
 After all network configuration, scheduling and post-simulation procedure specifications are
done, the only thing left is to run the simulation. This is done by $ns run.

RESULT:

Thus the study of ns2 is done successfully.

St.Joseph’s College of Engineering 33


CS8581-Networks Lab Department of CSE 2019-2020

EX:No: 6 B Simulation of Congestion Control Algorithms using NS

AIM:
To simulate a link failure and observe the congestion control algorithm using NS2.

ALGORITHM:
1. Create a simulation object
2. Set routing protocol to routing
3. Trace packets and all links onto NAM trace and to trace file
4. Create right nodes
5. Describe their layout topology as octagon
6. Add a sink agent to node
7. Connect source and sink.

PROGRAM:
set ns [new Simulator]
set nr [open thro_red.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0 }
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
$ns duplex-link $n0 $n3 1Mb 10ms RED
$ns duplex-link $n1 $n3 1Mb 10ms RED
$ns duplex-link $n2 $n3 1Mb 10ms RED
$ns duplex-link $n3 $n4 1Mb 10ms RED
$ns duplex-link $n4 $n5 1Mb 10ms RED
$ns duplex-link $n4 $n6 1Mb 10ms RED
$ns duplex-link $n4 $n7 1Mb 10ms RED
$ns duplex-link-op $n0 $n3 orient right-up
$ns duplex-link-op $n3 $n4 orient middle
$ns duplex-link-op $n2 $n3 orient right-down
$ns duplex-link-op $n4 $n5 orient right-up
$ns duplex-link-op $n4 $n7 orient right-down
$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link-op $n6 $n4 orient left
set udp0 [new Agent/UDP]

St.Joseph’s College of Engineering 34


CS8581-Networks Lab Department of CSE 2019-2020

$ns attach-agent $n2 $udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n5 $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n6 $null0
$ns connect $udp1 $null0
set udp2 [new Agent/UDP]
$ns attach-agent $n0 $udp2
set cbr2 [new Application/Traffic/CBR]
$cbr2 set packet size_ 500
$cbr2 set interval_ 0.005
$cbr2 attach-agent $udp2
set null0 [new Agent/Null]
$ns attach-agent $n7 $null0
$ns connect $udp2 $null0
$udp0 set fid_ 1
$udp1 set fid_ 2
$udp2 set fid_ 3
$ns color 1 Red
$ns color 2 Green
$ns color 2 Blue
$ns at 0.1 "$cbr0 start"
$ns at 0.2 "$cbr1 start"
$ns at 0.5 "$cbr2 start"
$ns at 4.0 "$cbr2 stop"
$ns at 4.2 "$cbr1 stop"
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run

St.Joseph’s College of Engineering 35


CS8581-Networks Lab Department of CSE 2019-2020

Output:

RESULT:
Thus the program for Congestion control is implemented in NS2 sucessfully.

St.Joseph’s College of Engineering 36


CS8581-Networks Lab Department of CSE 2019-2020

EX:No: 7 Study of TCP/UDP performance using Simulation tool.

Aim:
The aim is to study the performance of TCP/UDP using Simulation tool(NS2).

DESCRIPTION:

Network Simulator (Version 2), widely known as NS2,simulation tool which is meant for studying
dynamic nature of communication i.e. for both wired and wireless network functions and for routing
algorithms, TCP, UDP protocols. Basically it provides specific way of simulating such network
protocols.
TCP
The important protocol is Transmission Control Protocol (TCP) used for transmission in a network.
Internet widely uses TCP protocol for data transmission in communication network. In order to
perform transmission connection is established between the client and the server. Connection is
initiated by the Client and sends Sequence number along with the segment. So the Server
acknowledges it back with its own Sequence number and ACK of client’s segment which is one more
than client’s Sequence number. Client after receiving ACK of its segment sends an acknowledgement
of Server’s response.
UDP
The User Datagram Protocol (UDP) is simplest Transport Layer communication protocol available of
the TCP/IP protocol suite. Communication mechanism involved is minimum. UDP is an unreliable
transport protocol which uses IP services to provide best delivery mechanism. In UDP, there is no
generation of acknowledgement of received packets to sender and senders do not wait for any
acknowledgement in turn of packet. This makes UDP protocol unreliable on processing. UDP is
implemented where packet acknowledgement have same significance on bandwidth as that actual
data. In case of video streaming, thousands of packets are generated towards its users.
Acknowledging all those packets is troublesome and which results in huge amount of bandwidth
wastage.

METHODOLOGY FOR PERFORMANCE MEASURES:


The network is simulated using NS2 software. In order to simulate the algorithm contains the
following steps
1. New simulator is created.
2. Files are opened to store simulation results.
3. Nodes are created such as n0, n1, n2, n3, n4 and n5.
4. Links are established between all the nodes present
5. Transport agents are created, transport agents might be TCP, UDP or variants of TCP.
6. Connection is established between the transport agents used in the network.
7. Later traffic agents are created.
8. Once the traffic agents are created finish procedure is written.
9. Simulation time or the run time is set.
10. Finally, Simulation is performed.

Performance measure Using TCP


In this scenario, for the above proposed network TCP protocol is connected to all source nodes and
the bandwidth of links are kept constant. Throughputs and efficiency are calculated for bandwidth =
0.5mb and the efficiency is 75%

St.Joseph’s College of Engineering 37


CS8581-Networks Lab Department of CSE 2019-2020

Performace measures Using UDP


In this scenario, for the above proposed network UDP protocol is connected to all source nodes and
the bandwidth
of links are kept constant. Throughput and efficiency are calculated.

Result:
Thus the study for the performance measures of TCP and UDP is done successfully.

St.Joseph’s College of Engineering 38


CS8581-Networks Lab Department of CSE 2019-2020

EX:No: 8A Simulation of Distance Vector Routing Algorithm

AIM:
To simulate and study the Distance Vector routing algorithm using simulation.

SOFTWARE REQUIRED:
NS-2
THEORY:
Distance Vector Routing is one of the routing algorithm in a Wide Area Network for computing
shortest path
between source and destination. The Router is one main devices used in a wide area network. The
main task of
the router is Routing. It forms the routing table and delivers the packets depending upon the routes
in the tableeither directly or via an intermediate devices.
Each router initially has information about its all neighbors. Then this information will be shared
among nodes.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on
trace file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose distance vector routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.

PROGRAM:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0
}
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }

St.Joseph’s College of Engineering 39


CS8581-Networks Lab Department of CSE 2019-2020

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


$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto DV
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run

St.Joseph’s College of Engineering 40


CS8581-Networks Lab Department of CSE 2019-2020

RESULT:
Thus the Distance Vector routing algorithm is implemented successfully.

St.Joseph’s College of Engineering 41


CS8581-Networks Lab Department of CSE 2019-2020

EX:No: 8 A Simulation of Link State algorithm

AIM:
To simulate and study the link state routing algorithm using simulation.

SOFTWARE REQUIRED:
NS-2

THEORY:
In link state routing, each router shares its knowledge of its neighborhood with every other router in
the internet work. (i) Knowledge about Neighborhood: Instead of sending its entire routing table a
router sends info about its neighborhood only. (ii) To all Routers: each router sends this information
to every other router on the internet work not just to its neighbor .It does so by a process called
flooding. (iii)Information sharing when there is a change: Each router sends out information about
the neighbors when there is change.

PROCEDURE:
The Dijkstra algorithm follows four steps to discover what is called the shortest path tree(routing
table) for each router:The algorithm begins to build the tree by identifying its roots. The root router’s
trees the router itself. The algorithm then attaches all nodes that can be reached from the root. The
algorithm compares the tree’s temporary arcs and identifies the arc with the lowest cumulative cost.
This arc and the node to which it connects are now a permanent part of the shortest path tree. The
algorithm examines the database and identifies every node that can be reached from its chosen node.
These nodes and their arcs are added temporarily to the tree.
The last two steps are repeated until every node in the network has become a permanent part of the
tree.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on
trace file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose Link state routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.

PROGRAM:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0

St.Joseph’s College of Engineering 42


CS8581-Networks Lab Department of CSE 2019-2020

}
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto LS
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run

St.Joseph’s College of Engineering 43


CS8581-Networks Lab Department of CSE 2019-2020

RESULT
Thus the simulation of Link State routing algorithm is implemented in NS2 sucessfully.

St.Joseph’s College of Engineering 44


CS8581-Networks Lab Department of CSE 2019-2020

Ex.No.9 Performance Evaluvation of routing protocols using Simulation tool

AIM:
To evaluate the performance of routing protocols using NS2 simulation tool.

ALGORITHM:
1. Set ns as new simulator
2. Create a simulation for multicast routing protocol
3. Create nodes with duplex link
4. Allocate multicast addresses
5. Create multicast capable nodes
6. set RV and bootstrap points
7. Configure Multicast protocol
8. Attach Transport agent for the traffic source
9. Create receiver and set receiver

PROGRAM:

set ns [new Simulator]


$ns multicast
set f [open out.tr w]
$ns trace-all $f
$ns namtrace-all [open out.nam w]
$ns color 1 red
# the nam colors for the prune packets
$ns color 30 purple
# the nam colors for the graft packets
$ns color 31 green
# allocate a multicast address;
set group [Node allocaddr]
# nod is the number of nodes
set nod 6
# create multicast capable nodes;
for {set i 1} {$i <= $nod} {incr i} {
set n($i) [$ns node]
}
#Create links between the nodes
$ns duplex-link $n(1) $n(2) 0.3Mb 10ms DropTail
$ns duplex-link $n(2) $n(3) 0.3Mb 10ms DropTail
$ns duplex-link $n(2) $n(4) 0.5Mb 10ms DropTail
$ns duplex-link $n(2) $n(5) 0.3Mb 10ms DropTail
$ns duplex-link $n(3) $n(4) 0.3Mb 10ms DropTail
$ns duplex-link $n(4) $n(5) 0.5Mb 10ms DropTail
$ns duplex-link $n(4) $n(6) 0.5Mb 10ms DropTail
$ns duplex-link $n(5) $n(6) 0.5Mb 10ms DropTail
# configure multicast protocol;
set mproto CtrMcast
# all nodes will contain multicast protocol agents;
set mrthandle [$ns mrtproto $mproto]

# set RV and bootstrap points


$mrthandle set_c_rp $n(5)
# $mrthandle set_c_bsr $n(1):0 $n(3):1

set udp1 [new Agent/UDP]

St.Joseph’s College of Engineering 45


CS8581-Networks Lab Department of CSE 2019-2020

set udp2 [new Agent/UDP]

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


$ns attach-agent $n(2) $udp2

set src1 [new Application/Traffic/CBR]


$src1 attach-agent $udp1
$udp1 set dst_addr_ $group
$udp1 set dst_port_ 0
$src1 set random_ false

set src2 [new Application/Traffic/CBR]


$src2 attach-agent $udp2
$udp2 set dst_addr_ $group
$udp2 set dst_port_ 1
$src2 set random_ false

# create receiver agents


set rcvr [new Agent/LossMonitor]

# joining and leaving the group;


$ns at 0.6 "$n(3) join-group $rcvr $group"
$ns at 1.3 "$n(4) join-group $rcvr $group"
$ns at 1.6 "$n(5) join-group $rcvr $group"
$ns at 1.9 "$n(4) leave-group $rcvr $group"
$ns at 2.3 "$n(6) join-group $rcvr $group"
$ns at 3.5 "$n(3) leave-group $rcvr $group"

$ns at 0.4 "$src1 start"


$ns at 2.0 "$src2 start"

$ns at 4.0 "finish"

proc finish {} {
global ns
$ns flush-trace
exec nam out.nam &
exit 0
}

$ns run

St.Joseph’s College of Engineering 46


CS8581-Networks Lab Department of CSE 2019-2020

RESULT
Thus the program for multicast routing protocol has been implemented successfully in NS2.

St.Joseph’s College of Engineering 47


CS8581-Networks Lab Department of CSE 2019-2020

Ex.No.10 Simulation of Error Correction Code(CRC)

AIM:
To simulate Error Correction Code (CRC).

ALGORITHM:

1. Get the input in the form of bits.


2. Append zeros as redundancy bits.
3. Divide the appended data using a divisor polynomial.
4. The resulting data should be transmitted to the receiver.
5. At the receiver the received data is entered.
6. The same process is repeated at the receiver.
7. If the remainder is zero there is no error otherwise there is some error in the received bits
8. Run the program.

PROGRAM:
import java.util.*;

class CRC {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n;

//Accept the input


System.out.println("Enter the size of the data:");
n = scan.nextInt();
int data[] = new int[n];
System.out.println("Enter the data, bit by bit:");
for(int i=0 ; i < n ; i++) {
System.out.println("Enter bit number " + (n-i) + ":");
data[i] = scan.nextInt();
}

// Accept the divisor


System.out.println("Enter the size of the divisor:");
n = scan.nextInt();
int divisor[] = new int[n];
System.out.println("Enter the divisor, bit by bit:");
for(int i=0 ; i < n ; i++) {
System.out.println("Enter bit number " + (n-i) + ":");
divisor[i] = scan.nextInt();
}

// Divide the inputted data by the inputted divisor


// Store the remainder that is returned by the method
int remainder[] = divide(data, divisor);
for(int i=0 ; i < remainder.length-1 ; i++) {
System.out.print(remainder[i]);
}
System.out.println("\nThe CRC code generated is:");

for(int i=0 ; i < data.length ; i++) {


System.out.print(data[i]);
}
for(int i=0 ; i < remainder.length-1 ; i++) {
System.out.print(remainder[i]);
}
System.out.println();

St.Joseph’s College of Engineering 48


CS8581-Networks Lab Department of CSE 2019-2020

// Create a new array


// It will have the remainder generated by the above method appended
// to the inputted data
int sent_data[] = new int[data.length + remainder.length - 1];
System.out.println("Enter the data to be sent:");
for(int i=0 ; i < sent_data.length ; i++) {
System.out.println("Enter bit number " + (sent_data.length-i)
+ ":");
sent_data[i] = scan.nextInt();
}
receive(sent_data, divisor);
}

static int[] divide(int old_data[], int divisor[]) {


int remainder[] , i;
int data[] = new int[old_data.length + divisor.length];
System.arraycopy(old_data, 0, data, 0, old_data.length);
// Remainder array stores the remainder
remainder = new int[divisor.length];
// Initially, remainder's bits will be set to the data bits
System.arraycopy(data, 0, remainder, 0, divisor.length);

// Loop runs for same number of times as number of bits of data


// This loop will continuously exor the bits of the remainder and
// divisor
for(i=0 ; i < old_data.length ; i++) {
System.out.println((i+1) + ".) First data bit is : "
+ remainder[0]);
System.out.print("Remainder : ");
if(remainder[0] == 1) {
// We have to exor the remainder bits with divisor bits
for(int j=1 ; j < divisor.length ; j++) {
remainder[j-1] = exor(remainder[j], divisor[j]);
System.out.print(remainder[j-1]);
}
}
else {
// We have to exor the remainder bits with 0
for(int j=1 ; j < divisor.length ; j++) {
remainder[j-1] = exor(remainder[j], 0);
System.out.print(remainder[j-1]);
}
}
// The last bit of the remainder will be taken from the data
// This is the 'carry' taken from the dividend after every step
// of division
remainder[divisor.length-1] = data[i+divisor.length];
System.out.println(remainder[divisor.length-1]);
}
return remainder;
}

static int exor(int a, int b) {


// This simple function returns the exor of two bits
if(a == b) {
return 0;
}
return 1;
}

St.Joseph’s College of Engineering 49


CS8581-Networks Lab Department of CSE 2019-2020

static void receive(int data[], int divisor[]) {


// This is the receiver method
// It accepts the data and divisor (although the receiver already has
// the divisor value stored, with no need for the sender to resend it)
int remainder[] = divide(data, divisor);
// Division is done
for(int i=0 ; i < remainder.length ; i++) {
if(remainder[i] != 0) {
// If remainder is not zero then there is an error
System.out.println("There is an error in received data...");
return;
}
}
//Otherwise there is no error in the received data
System.out.println("Data was received without any error.");
}
}
[user@localhost ~]$ javac CRC.java
[user@localhost ~]$ java CRC
Enter the size of the data:
8
Enter the data, bit by bit:
Enter bit number 8:
0
Enter bit number 7:
0
Enter bit number 6:
1
Enter bit number 5:
0
Enter bit number 4:
0
Enter bit number 3:
0
Enter bit number 2:
0
Enter bit number 1:
0
Enter the size of the divisor:
4
Enter the divisor, bit by bit:
Enter bit number 4:
1
Enter bit number 3:
1
Enter bit number 2:
0
Enter bit number 1:
0
1.) First data bit is : 0
Remainder : 0100
2.) First data bit is : 0
Remainder : 1000
3.) First data bit is : 1
Remainder : 1000
4.) First data bit is : 1
Remainder : 1000
5.) First data bit is : 1
Remainder : 1000

St.Joseph’s College of Engineering 50


CS8581-Networks Lab Department of CSE 2019-2020

6.) First data bit is : 1


Remainder : 1000
7.) First data bit is : 1
Remainder : 1000
8.) First data bit is : 1
Remainder : 1000
100
The CRC code generated is:
00100000100
Enter the data to be sent:
Enter bit number 11:
1
Enter bit number 10:
0
Enter bit number 9:
0
Enter bit number 8:
0
Enter bit number 7:
0
Enter bit number 6:
1
Enter bit number 5:
0
Enter bit number 4:
0
Enter bit number 3:
0
Enter bit number 2:
0
Enter bit number 1:
0
1.) First data bit is : 1
Remainder : 1000
2.) First data bit is : 1
Remainder : 1001
3.) First data bit is : 1
Remainder : 1010
4.) First data bit is : 1
Remainder : 1100
5.) First data bit is : 1
Remainder : 0000
6.) First data bit is : 0
Remainder : 0000
7.) First data bit is : 0
Remainder : 0000
8.) First data bit is : 0
Remainder : 0000
9.) First data bit is : 0
Remainder : 0000
10.) First data bit is : 0
Remainder : 0000
11.) First data bit is : 0
Remainder : 0000
Data received without any error
RESULT:
Thus the program for Simulation of Error correction code using CRC is implemented successfully.

St.Joseph’s College of Engineering 51


CS8581-Networks Lab Department of CSE 2019-2020

EX.No.11 Simulate the performance of Go Back N protocol using NS2

AIM:
To Simulate and to study of Go Back N protocol
THEORY:
Go Back N is a connection oriented transmission. The sender transmits the frames continuously. Each frame in
the buffer has a sequence number starting from 1 and increasing up to the window size. The sender has a
window i.e. a buffer to store the frames. This buffer size is the number of frames to be transmitted continuously.
The size of the window depends on the protocol designer.

ALGORITHM :

1. The source node transmits the frames continuously.


2. Each frame in the buffer has a sequence number starting from 1 and increasing up to the window size.
3. The source node has a window i.e. a buffer to store the frames. This buffer size is the number of frames
to be transmitted continuously.
4. The size of the window depends on the protocol designer.
5. For the first frame, the receiving node forms a positive acknowledgement if the frame is received
without error.
6. If subsequent frames are received without error (up to window size) cumulative positive
acknowledgement is formed.
7. If the subsequent frame is received with error, the cumulative acknowledgment error-free frames are
transmitted. If in the same window two frames or more frames are received with error, the second and
the subsequent error frames are neglected. Similarly even the frames received without error after the
receipt of a frame with error are neglected.
8. The source node retransmits all frames of window from the first error frame.
9. If the frames are errorless in the next transmission and if the acknowledgment is error free, the window
slides by the number of error-free frames being transmitted.
10. If the acknowledgment is transmitted with error, all the frames of window at source are retransmitted,
and window doesn’t slide.
11. This concept of repeating the transmission from the first error frame in the window is called as
GOBACKN transmission flow control protocol

PROGRAM FOR GOBACK N:

#send packets one by one


set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n0 color "purple"
$n1 color "purple"
$n2 color "violet"
$n3 color "violet"
$n4 color "chocolate"
$n5 color "chocolate"
$n0 shape box ;
$n1 shape box ;
$n2 shape box ;
$n3 shape box ;
$n4 shape box ;
$n5 shape box ;
$ns at 0.0 "$n0 label SYS0"

St.Joseph’s College of Engineering 52


CS8581-Networks Lab Department of CSE 2019-2020

$ns at 0.0 "$n1 label SYS1"


$ns at 0.0 "$n2 label SYS2"
$ns at 0.0 "$n3 label SYS3"
$ns at 0.0 "$n4 label SYS4"
$ns at 0.0 "$n5 label SYS5"
set nf [open goback.nam w]
$ns namtrace-all $nf
set f [open goback.tr w]
$ns trace-all $f
$ns duplex-link $n0 $n2 1Mb 20ms DropTail
$ns duplex-link-op $n0 $n2 orient right-down
$ns queue-limit $n0 $n2 5
$ns duplex-link $n1 $n2 1Mb 20ms DropTail
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link $n2 $n3 1Mb 20ms DropTail
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link $n3 $n4 1Mb 20ms DropTail
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link $n3 $n5 1Mb 20ms DropTail
$ns duplex-link-op $n3 $n5 orient right-down
Agent/TCP set_nam_tracevar_true
set tcp [new Agent/TCP]
$tcp set fid 1
$ns attach-agent $n1 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 0.05 "$ftp start"
$ns at 0.06 "$tcp set windowlnit 6"
$ns at 0.06 "$tcp set maxcwnd 6"
$ns at 0.25 "$ns queue-limit $n3 $n4 0"
$ns at 0.26 "$ns queue-limit $n3 $n4 10"
$ns at 0.305 "$tcp set windowlnit 4"
$ns at 0.305 "$tcp set maxcwnd 4"
$ns at 0.368 "$ns detach-agent $n1 $tcp ; $ns detach-agent $n4 $sink"
$ns at 1.5 "finish"
$ns at 0.0 "$ns trace-annotate \"Goback N end\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.01\""
$ns at 0.06 "$ns trace-annotate \"Send 6Packets from SYS1 to SYS4\""
$ns at 0.26 "$ns trace-annotate \"Error Occurs for 4th packet so not sent
ack for the Packet\""
$ns at 0.30 "$ns trace-annotate \"Retransmit Packet_4 to 6\""
$ns at 1.0 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
puts "filtering..."
#exec tclsh../bin/namfilter.tcl goback.nam
#puts "running nam..."
exec nam goback.nam &
exit 0
}
$ns run

St.Joseph’s College of Engineering 53


CS8581-Networks Lab Department of CSE 2019-2020

RESULT:
Thus the program for GO BACK N Protocol is implemented successfully in NS2.

St.Joseph’s College of Engineering 54


CS8581-Networks Lab Department of CSE 2019-2020

Ex:No:11 B Simulate the performance of Stop wait protocol using NS2

AIM:
To simulate the performance of Stop wait protocol using ns2.

ALGORITHM:
Step 1: Start the program
Step 2: Create the trace file and NAM file.
Step 3: Setup the topology object
Step 4: Create nodes and set duplex links between the nodes.
Step 5: Create nodes and attach them to the queue, DROPTAIL
Step 6: Configure the nodes and provides initial location of nodes. Generation of movements is done.
Step 7: Setup a TCP Connection between nodes
Step 8: Define a initialize positions for the nam window.
Step 9: Telling nodes when the simulation ends
Step 10: Ending nam and the simulation

PROGRAM:
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

$n0 color "purple"


$n1 color "purple"
$n2 color "violet"
$n3 color "violet"
$n4 color "chocolate"
$n5 color "chocolate"

set f [open stopwait.tr w]


$ns trace-all $f
set nf [open stopwait.nam w]
$ns namtrace-all $nf

$ns at 0.0 "$n0 label SYS0"


$ns at 0.0 "$n1 label SYS1"
$ns at 0.0 "$n2 label SYS2"
$ns at 0.0 "$n3 label SYS3"
$ns at 0.0 "$n4 label SYS4"
$ns at 0.0 "$n5 label SYS5"

$ns duplex-link $n0 $n2 0.2Mb 20ms DropTail


$ns duplex-link $n1 $n2 0.2Mb 20ms DropTail
$ns duplex-link $n2 $n3 0.2Mb 20ms DropTail

St.Joseph’s College of Engineering 55


CS8581-Networks Lab Department of CSE 2019-2020

$ns duplex-link $n3 $n4 0.2Mb 20ms DropTail


$ns duplex-link $n3 $n5 0.2Mb 20ms DropTail

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


$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down
$ns queue-limit $n0 $n2 10

Agent/TCP set_nam_tracevar_true
set tcp [new Agent/TCP]
$tcp set window 1
$tcp set maxcwnd 1
$tcp set fid 1
$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n5 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
$tcp tracevar cwnd

$ns at 0.1 "$ftp start"


$ns at 0.53 "$ns queue-limit $n3 $n5 0"
$ns at 0.80 "$ns queue-limit $n3 $n5 5"
$ns at 2.0 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n5 $sink"
$ns at 2.5 "finish"

#$ns at 0.0 "$ns trace-annotate \"STOPWAIT\""


$ns at 0.01 "$ns trace-annotate \"FTP starts at 0.01\""
$ns at 0.10 "$ns trace-annotate \"Send Request SYS0 to SYS5\""
$ns at 0.18 "$ns trace-annotate \"Receive Request SYS5 to SYS0\""
$ns at 0.24 "$ns trace-annotate \"Send Packet_0 SYS0 to SYS5\""
$ns at 0.42 "$ns trace-annotate \"Receive Ack_0\""
$ns at 0.48 "$ns trace-annotate \"Send Packet_1\""
$ns at 0.60 "$ns trace-annotate \"Disconnect N2 So loss the packet1\""
$ns at 0.67 "$ns trace-annotate \"Waiting for Ack_1\""
$ns at 0.95 "$ns trace-annotate \"Send Packet_1 again\""
$ns at 1.95 "$ns trace-annotate \"Deattach SYS3,Packet_1 again\""
$ns at 2.09 "$ns trace-annotate \"Receive Ack_1\""
$ns at 2.10 "$ns trace-annotate \"SEnd Packet_2\""
$ns at 2.38 "$ns trace-annotate \"Receive Ack_2\""
$ns at 2.5 "$ns trace-annotate \"FTP stops\""

proc finish {} {
global ns nf

St.Joseph’s College of Engineering 56


CS8581-Networks Lab Department of CSE 2019-2020

$ns flush-trace
close $nf
exec nam stopwait.nam &
exit 0
}
$ns run

OUTPUT:
STOP WAIT PROTOCOL:

RESULT:
Thus the program to implement Stopwait protocol in NS2 sucessfully.

St.Joseph’s College of Engineering 57

You might also like