CS8581 - Computer Networks Lab (PTR@9119) Manual

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

https://www.ptrcet.

org Department of Computer Science and Engineering

Thanapandiyan Nagar, AIIMS Road, Austinpatti,


Madurai – 8.

LAB MANUAL
Regulation : 2017
Branch : B.E., (CSE)
Year & Semester : III Year / V Semester

CS8581 – NETWORKS LABORATORY 1


https://www.ptrcet.org Department of Computer Science and Engineering

ANNA UNIVERSITY, CHENNAI.

AFFILIATED INSTITUTIONS

REGULATIONS – 2017
CHOICE BASED CREDIT SYSTEM
CS8581 – NETWORKS LABORATORY

LIST OF EXPERIMENTS
1. Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute.
Capture ping and traceroute PDUs using a network protocol analyzer and examine.
2. Write a HTTP web client program to download a web page using TCP sockets.
3. Applications using TCP sockets like:
 Echo client and echo server
 Chat
 File Transfer
4. Simulation of DNS using UDP sockets.
5. Write a code simulating ARP /RARP protocols.
6. Study of Network simulator (NS) and Simulation of Congestion Control Algorithms
using NS.
7. Study of TCP/UDP performance using Simulation tool.
8. Simulation of Distance Vector/ Link State Routing algorithm.
9. Performance evaluation of Routing protocols using Simulation tool.
10. Simulation of error correction code (like CRC).

TOTAL : 60 PERIODS

CS8581 – NETWORKS LABORATORY 2


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 1

LEARN TO USE COMMANDS LIKE NETSTAT, IPCONFIG,


NSLOOKUP AND TRACEROUTE

Aim :
To Learn to use commands like netstat, ipconfig, nslookup and traceroute. Capture
ping and traceroute PDUs using a network protocol analyzer and examine them.

Command > netstat


 netstat (Network Statistics) is a common command line TCP/IP networking
utility available in most versions of Windows, Linux, UNIX and other operating
systems. netstat provides information and statistics about protocols in use and
current TCP/IP network connections.
General Syntax
> netstat [-a][-b][-e][-n][-o][-p proto][-r][-s][-x][-t]
[interval]

Parameters
Used without
displays active TCP connections.
parameters

-a Displays all connections and listening ports.

Displays the executable involved in creating each connection or listening


port. In some cases well-known executables host multiple independent
components, and in these cases the sequence of components involved in
-b creating the connection or listening port is displayed. In this case the
executable name is in [] at the bottom, on top is the component it called,
and so forth until TCP/IP was reached. Note that this option can be time-
consuming and will fail unless you have sufficient permissions.

-e Displays Ethernet statistics. This may be combined with the -s option.

-n Displays addresses and port numbers in numerical form.

CS8581 – NETWORKS LABORATORY 3


https://www.ptrcet.org Department of Computer Science and Engineering

Displays the owning process ID associated with each connection. This


-o
parameter can be combined with -a, -n, and -p.

Shows connections for the protocol specified by proto; proto may be any
of: TCP, UDP, TCPv6, or UDPv6. If used with the -s option to display
-p proto
per-protocol statistics, proto may be any of: IP, IPv6, ICMP, ICMPv6,
TCP, TCPv6, UDP, or UDPv6.

-r Display the Routing table.

Displays per-protocol statistics. By default, statistics are shown for IP,


-s IPv6, ICMP,ICMPv6, TCP, TCPv6, UDP, and UDPv6; the -p option
may be used to specify a subset of the default.

When used in conjunction with -b, will display sequence of components


-v
involved in creating the connection or listening port for all executables.

Redisplays selected statistics, pausing interval seconds between each


interval display. Press CTRL+C to stop redisplaying statistics. If omitted, netstat
will print the current configuration information once.

Command > ipconfig


 ipconfig (Internet Protocol Configuration) displays all current TCP/IP network
configuration values and refreshes Dynamic Host Configuration Protocol (DHCP) and
Domain Name System (DNS) settings. Used without parameters, ipconfig
displays Internet Protocol version 4 (IPV4) and IPV6 addresses, subnet mask and
default gateway for all adapters.

General Syntax
> ipconfig [/allcompartments] [/all] [/renew [<Adapter>]]

[/release [Adapter]] [/renew6 [<Adapter>]] [/release6
[<Adapter>]] [/flushdns] [/displaydns][/registerdns]
[/showclassid <Adapter] [/setclassid <Adapter> [<ClassID>]]

Parameters
Displays the full TCP/IP configuration for all adapters. Adapters can
/all represent physical interfaces, such as installed network adapters, or
logical interfaces, such as dial-up connections.
/allcompartments Displays the full TCP/IP configuration for all compartments.

CS8581 – NETWORKS LABORATORY 4


https://www.ptrcet.org Department of Computer Science and Engineering

Displays the contents of the DNS client resolver cache, which


includes both entries preloaded from the local Hosts file and any
recently obtained resource records for name queries resolved by the
-displaydns
computer. The DNS client service uses this information to resolve
frequently queried names quickly, before querying its configured
DNS servers.

Flushes and resets the contents of the DNS client resolver cache.
During DNS troubleshooting, you can use this procedure to discard
/flushdns
negative cache entries from the cache, as well as any other entries
that have been added dynamically.

Initiates manual dynamic registration for the DNS names and IP


addresses that are configured at a computer. You can use this
parameter to troubleshoot a failed DNS name registration or resolve
/registerdns a dynamic update problem between a client and the DNS server
without rebooting the client computer. The DNS settings in the
advanced properties of the TCP/IP protocol determine which names
are registered in DNS.

Sends a DHCPRELEASE message to the DHCP server to release


the current DHCP configuration and discard the IP address
configuration for either all adapters (if an adapter is not specified)
/release [<Adapter>] or for a specific adapter if the Adapter parameter is included. This
parameter disables TCP/IP for adapters configured to obtain an IP
address automatically. To specify an adapter name, type the adapter
name that appears when you use ipconfig without parameters.

Renews DHCP configuration for all adapters (if an adapter is not


specified) or for a specific adapter if the Adapter parameter is
included. This parameter is available only on computers with
/renew[<Adapter>]
adapters that are configured to obtain an IP address automatically.
To specify an adapter name, type the adapter name that appears
when you use ipconfig without parameters.

Configures the DHCP class ID for a specified adapter. To set the


DHCP class ID for all adapters, use the asterisk (*) wildcard
character in place of Adapter. This parameter is available only on
/setclassid<Adapter>[]
computers with adapters that are configured to obtain an IP address
automatically. If a DHCP class ID is not specified, the current class
ID is removed.

Displays the DHCP class ID for a specified adapter. To see the


DHCP class ID for all adapters, use the asterisk (*) wildcard
/showclassid<Adapter> character in place of Adapter. This parameter is available only on
computers with adapters that are configured to obtain an IP address
automatically.

CS8581 – NETWORKS LABORATORY 5


https://www.ptrcet.org Department of Computer Science and Engineering

Sample output : Command > netstat


C:\Users\PTR-PC>netstat

Active Connections

Proto Local Address Foreign Address State

TCP 192.168.43.88:49905 40.81.30.101:https ESTABLISHED


TCP 192.168.43.88:49906 a23-1-36-182:https ESTABLISHED
TCP 192.168.43.88:49907 relay-f5dee7c6:6568 TIME_WAIT
TCP 192.168.43.88:49909 a23-1-37-123:https ESTABLISHED
TCP 192.168.43.88:49910 maa03s23-in-f14:https TIME_WAIT
TCP 192.168.43.88:49911 relay-1db3655a:http ESTABLISHED
TCP 192.168.43.88:49913 a23-1-37-165:http ESTABLISHED
TCP 192.168.43.88:49914 a104-108-153-213:https ESTABLISHED
TCP 192.168.43.88:49916 137.116.151.74:https ESTABLISHED
TCP 192.168.43.88:49917 40.90.137.127:https ESTABLISHED
TCP 192.168.43.88:49918 40.90.137.127:https ESTABLISHED
TCP 192.168.43.88:49920 a104-86-189-97:http ESTABLISHED
TCP 192.168.43.88:49922 52.148.83.112:https ESTABLISHED
TCP 192.168.43.88:49923 a-0001:https ESTABLISHED
TCP 192.168.43.88:49925 40.119.211.203:https ESTABLISHED
TCP 192.168.43.88:49927 a23-211-142-190:https ESTABLISHED
TCP 192.168.43.88:49932 a23-77-61-199:https ESTABLISHED
TCP 192.168.43.88:49933 a23-1-37-55:https ESTABLISHED
TCP 192.168.43.88:49934 52.109.88.39:https ESTABLISHED
TCP 192.168.43.88:49935 a104-76-140-232:https ESTABLISHED
TCP 192.168.43.88:49936 a104-76-140-232:https ESTABLISHED
TCP 192.168.43.88:49937 ec2-13-127-35-230:https ESTABLISHED
TCP 192.168.43.88:49941 52.109.120.18:https ESTABLISHED
TCP 192.168.43.88:49942 ec2-13-127-35-230:https ESTABLISHED
TCP 192.168.43.88:49943 ec2-3-213-170-20:https CLOSE_WAIT
TCP 192.168.43.88:49944 ec2-13-235-141-20:https ESTABLISHED
TCP 192.168.43.88:49945 a104-76-140-232:https ESTABLISHED
TCP 192.168.43.88:49946 a104-76-140-232:https CLOSE_WAIT
TCP 192.168.43.88:49947 a104-76-140-232:https ESTABLISHED
TCP 192.168.43.88:49948 a104-76-140-232:https CLOSE_WAIT
TCP 192.168.43.88:49950 ec2-13-235-141-20:https ESTABLISHED

CS8581 – NETWORKS LABORATORY 6


https://www.ptrcet.org Department of Computer Science and Engineering

Sample output : Command > ipconfig


C:\Users\PTR-PC>ipconfig

Windows IP Configuration

Ethernet adapter Local Area Connection 1:


Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::a0a7:9420:781:6e15%18
IPv4 Address. . . . . . . . . . . : 192.168.43.88
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.43.1

Sample output : Command > ipconfig /all


C:\Users\PTR-PC>ipconfig /all

Windows IP Configuration
Host Name . . . . . . . . . . . . : PTR-PC
Primary Dns Suffix . . . . . . . :
Node Type . . . . . . . . . . . . : Hybrid
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No

Ethernet adapter Ethernet:


Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Realtek PCIe FE Family Controller
Physical Address. . . . . . . . . : 38-EA-A7-EB-5F-63
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes

Wireless LAN adapter Local Area Connection* 1:


Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Microsoft Wi-Fi Direct Virtual Adapter
Physical Address. . . . . . . . . : F4-B7-E2-40-6B-FF
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes

Wireless LAN adapter Wi-Fi:


Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Ralink RT3290 802.11bgn Wi-Fi Adapter
Physical Address. . . . . . . . . : F4-B7-E2-40-6B-FD
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::a0a7:9420:781:6e15%18(Preferred)
IPv4 Address. . . . . . . . . . . : 192.168.43.88(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Lease Obtained. . . . . . . . . . : Tuesday, July 8, 2019 2:08:42 PM
Lease Expires . . . . . . . . . . : Tuesday, July 8, 2019 3:25:44 PM
Default Gateway . . . . . . . . . : 192.168.43.1
DHCP Server . . . . . . . . . . . : 192.168.43.1
DHCPv6 IAID . . . . . . . . . . . : 116701154
DHCPv6 Client DUID. . . . . . . . : 00-01-00-07-23-4A-05-91-02-0C-32-37-60-37

CS8581 – NETWORKS LABORATORY 7


https://www.ptrcet.org Department of Computer Science and Engineering

DNS Servers . . . . . . . . . . . : 192.168.43.1


NetBIOS over Tcpip. . . . . . . . : Enabled
Sample output : Command > ipconfig /displaydns

C:\Users\PTR-PC>ipconfig /displaydns

Windows IP Configuration

1.0.0.127.in-addr.arpa
----------------------------------------
Record Name . . . . . : 1.0.0.127.in-addr.arpa.
Record Type . . . . . : 12
Time To Live . . . . : 86400
Data Length . . . . . : 8
Section . . . . . . . : Answer
PTR Record . . . . . : localhost

123.37.1.23.in-addr.arpa
----------------------------------------
Record Name . . . . . : 123.37.1.23.in-addr.arpa
Record Type . . . . . : 12
Time To Live . . . . : 25681
Data Length . . . . . : 8
Section . . . . . . . : Answer
PTR Record . . . . . : a23-1-37-123.deploy.static.akamaitechnologies.com

localhost
----------------------------------------
Record Name . . . . . : localhost
Record Type . . . . . : 1
Time To Live . . . . : 1200
Data Length . . . . . : 4
Section . . . . . . . : Question
A (Host) Record . . . : 127.0.0.1

localhost
----------------------------------------
Record Name . . . . . : localhost
Record Type . . . . . : 28
Time To Live . . . . : 1200
Data Length . . . . . : 16
Section . . . . . . . : Question
AAAA Record . . . . . : ::1

relay-1db3655a.net.anydesk.com
----------------------------------------
Record Name . . . . . : relay-1db3655a.net.anydesk.com
Record Type . . . . . : 1
Time To Live . . . . : 78432
Data Length . . . . . : 4
Section . . . . . . . : Answer
A (Host) Record . . . : 54.36.108.171

CS8581 – NETWORKS LABORATORY 8


https://www.ptrcet.org Department of Computer Science and Engineering

Command > nslookup


 nslookup (stands for “Name Server Lookup”) is a useful command for getting
information from DNS server. It is a network administration tool for querying the
Domain Name System (DNS) to obtain domain name or IP address mapping or any
other specific DNS record. It is also used to troubleshoot DNS related problems.
General Syntax
> nslookup [option]

[option]

> nslookup domain_name


nslookup followed by the domain name will display the “A Record” (IP
Address) of the domain. Use this command to find the address record for a domain. It
queries to domain name servers and get the details.

> nslookup IP_Address (Reverse DNS lookup)


We can also do the reverse DNS lookup by providing the IP Address as argument to
nslookup

> nslookup –type=soa domain_name (Lookup for an soa record)


SOA record (Start of Authority), provides the authoritative information about the
domain, the e-mail address of the domain admin, the domain serial number, etc…… .

> nslookup –type=ns domain_name (Lookup for an ns record)


NS (Name Server) record maps a domain name to a list of DNS servers authoritative
for that domain. It will output the name servers which are associated with the given
domain_name.

CS8581 – NETWORKS LABORATORY 9


https://www.ptrcet.org Department of Computer Science and Engineering

Sample output : Command > nslookup domain_name

C:\Users\PTR-PC>nslookup www.ptrcet.org
Server: UnKnown
Address: 192.168.43.1

Non-authoritative answer:
Name: ptrcet.org
Address: 208.91.199.125
Aliases: www.ptrcet.org

Sample output : Command > nslookup IP_Address

C:\Users\PTR-PC>nslookup 208.91.199.125
Server: UnKnown
Address: 192.168.43.1

Name: bh-9.webhostbox.net
Address: 208.91.199.125

Sample output : Command > nslookup –type=soa domain_name

C:\Users\PTR-PC>nslookup -type=soa ptrcet.org


Server: UnKnown
Address: 192.168.43.1

Non-authoritative answer:
ptrcet.org
primary name server = ns1.elysiumhosting.com
responsible mail addr = ka.sundaresh.gmail.com
serial = 2019090500
refresh = 3600 (1 hour)
retry = 7200 (2 hours)
expire = 1209600 (14 days)
default TTL = 86400 (1 day)

ptrcet.org nameserver = ns1.elysiumhosting.com


ptrcet.org nameserver = ns2.elysiumhosting.com

Sample output : Command > nslookup –type=ns domain_name

C:\Users\PTR-PC>nslookup -type=ns ptrcet.org


Server: UnKnown
Address: 192.168.43.1

Non-authoritative answer:
ptrcet.org nameserver = ns1.elysiumhosting.com

CS8581 – NETWORKS LABORATORY 10


https://www.ptrcet.org Department of Computer Science and Engineering

ptrcet.org nameserver = ns2.elysiumhosting.com


Command > ping
 ping command is usually used as a simple way to verify that a computer can
communicate over the network with another computer or network device. The ping
command operates by sending Internet Control Message Protocol (ICMP) Echo
Request messages to the destination computer and waiting for a response.
General Syntax
> ping [host_name or IP_Address or domain_name] [option]

[option]

-t Pings the specified host until stopped. To stop press “ctrl + C”


-a Resolve addresses to hostnames
-n Number of echo requests to send

Command > tracert


 tracert (Traceroute) is a command which can show us the path a packet of
information takes from our computer to one we specify. It will list all the routers it
passes through until it reaches its destination, or fails to and is discarded. In addition
to this, it will tell us how long each ‘hop’ from router to router takes.
General Syntax
> tracert [domain_name] [option]

[option]
This option prevents tracert from resolving IP_addresses to
-d
hostnames, often resulting in much faster results.

Specifies the maximum number of hops in the search for the


-h
target. If we don’t specify MaxHops, and a target has not been
MaxHops
found by 30 hops, tracert will stop looking.
-w We can specify the time, in milliseconds, to allow each reply
TimeOut before timeout.

Result :

CS8581 – NETWORKS LABORATORY 11


https://www.ptrcet.org Department of Computer Science and Engineering

Sample output : Command > ping domain_name

C:\Users\PTR-PC>ping www.ptrcet.org

Pinging ptrcet.org [208.91.199.125] with 32 bytes of data:


Reply from 208.91.199.125: bytes=32 time=502ms TTL=48
Reply from 208.91.199.125: bytes=32 time=451ms TTL=48
Reply from 208.91.199.125: bytes=32 time=314ms TTL=48
Reply from 208.91.199.125: bytes=32 time=350ms TTL=48

Ping statistics for 208.91.199.125:


Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 314ms, Maximum = 502ms, Average = 404ms

Sample output : Command > tracert domain_name

C:\Users\PTR-PC>tracert www.ptrcet.org

Tracing route to ptrcet.org [208.91.199.125]


over a maximum of 30 hops:

1 5 ms 1 ms 1 ms 192.168.43.1

2 * * * Request timed out.

3 96 ms 59 ms 43 ms 10.40.14.125

4 88 ms 48 ms 66 ms 10.0.66.157

5 105 ms 101 ms 42 ms 125.16.41.109

6 492 ms 325 ms 315 ms 125.62.187.113

7 506 ms 315 ms 319 ms 38.142.34.241

8 285 ms 282 ms 318 ms be3360.ccr42.lax01.atlas.cogentco.com [154.54.25.149]

9 313 ms 671 ms 557 ms be2932.ccr32.phx01.atlas.cogentco.com [154.54.45.161]

10 293 ms 327 ms 282 ms be2930.ccr21.elp01.atlas.cogentco.com [154.54.42.78]

11 316 ms 292 ms 389 ms be2301.ccr21.sat01.atlas.cogentco.com [154.54.5.173]

12 338 ms 303 ms 329 ms be2875.rcr51.aus02.atlas.cogentco.com [154.54.7.45]

13 * * * Request timed out.

14 * * * Request timed out.

15 432 ms 307 ms 327 ms bh-9.webhostbox.net [208.91.199.125]

Trace complete.

CS8581 – NETWORKS LABORATORY 12


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 2

HTTP WEB CLIENT PROGRAM TO DOWNLOAD


A WEB PAGE USING TCP SOCKETS

Aim :
To write a java program for HTTP web client program to Download a Web page
using TCP Sockets.

Algorithm :
1. Create a URL object and pass URL as string to download the web page.
URL url=new URL(pass url of webpage we 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 :
WebClient.java
import java.io.*;
import java.net.*;
public class WebClient
{
public static void main(String args[])throws Exception
{
URL url=new URL("http://www.ptrcet.org");
BufferedReader reader=new BufferedReader(new
InputStreamReader(url.openStream()));
BufferedWriter writer=new BufferedWriter(new
FileWriter("ptrorg.php"));
String line;
while((line=reader.readLine())!=null)
{
writer.write(line);

CS8581 – NETWORKS LABORATORY 13


https://www.ptrcet.org Department of Computer Science and Engineering

writer.newLine();
}
System.out.println(".------------------.");
System.out.println("| File Downloaded. |");
System.out.println(".------------------.");
reader.close();
writer.close();
}
}

Result :

Output :

CS8581 – NETWORKS LABORATORY 14


https://www.ptrcet.org Department of Computer Science and Engineering

C:\Users\PTR-PC\Desktop\Computer Networks\WebClient>javac
WebClient.java

C:\Users\PTR-PC\Desktop\Computer Networks\WebClient>java WebClient


.------------------.
| File Downloaded. |
.------------------.
(Downloaded webpage – ptrorg.php)
<!doctype html>
<html>
<head>
<script>

var isNS = (navigator.appName == "Netscape") ? 1 : 0;


if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
document.onkeydown = function(e) {
if (e.ctrlKey &&
(e.keyCode === 67 ||
e.keyCode === 86 ||
e.keyCode === 85 ||
e.keyCode === 117)) {
return false;
} else {
return true;

CS8581 – NETWORKS LABORATORY 15


https://www.ptrcet.org Department of Computer Science and Engineering

}
};
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script> <script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
document.onkeydown = function(e) {
if (e.ctrlKey &&
(e.keyCode === 67 ||
e.keyCode === 86 ||

CS8581 – NETWORKS LABORATORY 16


https://www.ptrcet.org Department of Computer Science and Engineering

e.keyCode === 85 ||
e.keyCode === 117)) {
return false;
} else {
return true;
}
};
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>
<meta http-equiv="Refresh" content="0; url=ptrorg.php" ">
</head>
<body>
</body>
</html>

CS8581 – NETWORKS LABORATORY 17


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 3 (a)

APPLICATIONS USING TCP SOCKETS LIKE


ECHO CLIENT AND ECHO SERVER

Aim :
To write a java program for applications using TCP Sockets like Echo Client and
Echo Server.
Algorithm :
1. Start the program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If our frames reach the server it will send ACK signal to client otherwise it will send
NACK signal to client.
6. Stop the program

Program :
EchoServer.java
//TCP Echo Client--tcpechoclient.java
import java.io.*;
import java.net.*;
public class EchoServer
{
public static void main(String args[]) throws Exception
{
try
{
ServerSocket sok =new ServerSocket(9999);
System.out.println(" Server is Ready To Receive a Message. ");
System.out.println(" Waiting ..... ");
Socket so=sok.accept();
if(so.isConnected()==true)
System.out.println(" Client Socket is Connected Succecfully. ");
InputStream in=so.getInputStream();
OutputStream ou=so.getOutputStream();
PrintWriter pr=new PrintWriter(ou);
BufferedReader buf=new BufferedReader(new InputStreamReader(in));
String str=buf.readLine();
System.out.println(" Message Received From Client : " + str);
System.out.println(" This Message is Forwarded To Client. ");
CS8581 – NETWORKS LABORATORY 18
https://www.ptrcet.org Department of Computer Science and Engineering

pr.println(str);
pr.flush();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}

EchoClient.java
//TCP Echo Client--tcpechoclient.java
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args)throws Exception
{
try
{
Socket sok = new Socket("localhost",9999);
if(sok.isConnected()==true)
System.out.println(" Server socket is connected Successfully.");
InputStream in=sok.getInputStream();
OutputStream out=sok.getOutputStream();
PrintWriter w = new PrintWriter(out);
BufferedReader br1 = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in));
String str1,str2;
System.out.println(" Enter the Message : ");
str1=br1.readLine();
w.println(str1);
w.flush();
System.out.println(" Message Send Successfully");
str2=br2.readLine();
System.out.println(" Message From Server : "+str2);
}
catch(Exception e)
{
System.out.println("Error : "+e.getMessage());
}
}
}

Result :
Output : (First run the Server_Program and then run Client_Program)

CS8581 – NETWORKS LABORATORY 19


https://www.ptrcet.org Department of Computer Science and Engineering

(EchoServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\Echo>javac EchoServer.java
C:\Users\PTR-PC\Desktop\Computer Networks\Echo>java EchoServer
Server is Ready To Receive a Message.
Waiting .....
Client Socket is Connected Succecfully.
Message Received From Client : Welcome to PTRCET
This Message is Forwarded To Client.

(EchoClient.java)
C:\Users\PTR-PC\Desktop\Computer Networks\Echo>javac EchoClient.java
C:\Users\PTR-PC\Desktop\Computer Networks\Echo>java EchoClient
Server socket is connected Successfully.
Enter the Message :
Welcome to PTRCET
Message Send Successfully
Message From Server : Welcome to PTRCET

CS8581 – NETWORKS LABORATORY 20


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 3 (b)

APPLICATIONS USING TCP SOCKETS LIKE


CHAT

Aim :
To write a java program implement a CHAT application, where the Client establishes
a connection with the server. The Client and Server can send as well as receive messages.
Both the Client and Server exchange messages.

Algorithm :
Server Client

1. Start the Program and create server 1. Start the Program and create a client
and client sockets. socket that connects to the required
2. Use input Streams to get message host and port.
from user. 2. Use input Streams to read message
3. Use output Streams to Send message given by server and print it.
to the Client. 3. Use input Streams; get the message
4. Wait for Client to display this from user to be given to the server..
message and write a new one to be 4. Use output Streams to write message
displayed by the server. to the server.
5. Display message given at Client 5. Stop the program
using input Streams read from
socket.
6. Stop the program.

Program :
ServerChat.java
import java.net.*;
import java.io.*;
public class ServerChat
{
public static void main( String args[]) throws Exception
{
ServerSocket srs = new ServerSocket(1234);
System.out.println("Server is running...");
Socket ss=srs.accept();

CS8581 – NETWORKS LABORATORY 21


https://www.ptrcet.org Department of Computer Science and Engineering

System.out.println("connection establised\n");
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("\nEnter 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);
}
}
}

ClientChat.java
import java.net.*;
import java.io.*;
public class ClientChat
{
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("\nEnter text..");
System.out.println(" if Client want to 'quit' type ==>exit");
String s1,s4=null;
while(!(s1=kb.readLine()).equals("exit"))
{

CS8581 – NETWORKS LABORATORY 22


https://www.ptrcet.org Department of Computer Science and Engineering

//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("\nEnter text ");
}
System.out.println("Terminated..");
cs.close();
dos.close();
kb.close();
}
}

Result :

Output : (First run the Server_Program and then run Client_Program)

(ServerChat.java)
CS8581 – NETWORKS LABORATORY 23
https://www.ptrcet.org Department of Computer Science and Engineering

C:\Users\PTR-PC\Desktop\Computer Networks\CHAT>javac ServerChat.java


C:\Users\PTR-PC\Desktop\Computer Networks\CHAT>java ServerChat
Server is running...
connection established

Client said : Welcome to PTRCET


Enter text
Welcome

Client said : What do you feel about Network Lab..??


Enter text
It is very interesting to learn

Client said : OK
Enter text
Bye
Terminated..

(ClientChat.java)
C:\Users\PTR-PC\Desktop\Computer Networks\CHAT>javac ClientChat.java
C:\Users\PTR-PC\Desktop\Computer Networks\CHAT>java ClientChat

Enter text..
if Client want to 'quit' type ==>exit
Welcome to PTRCET
Server said : Welcome

Enter text
What do you feel about Network Lab..??
Server said : It is very interesting to learn

Enter text
OK
Server said : Bye

Enter text
exit
Terminated..

CS8581 – NETWORKS LABORATORY 24


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 3 (c)

APPLICATIONS USING TCP SOCKETS LIKE


FILE TRANSFER

Aim :
To write a java program for File Transfer using TCP Sockets.

Algorithm :
Server Client

1. Import java packages and create 1. Import java packages and create
class file server. class file server.
2. Create a new server socket and bind 2. Create a new server socket and bind
it to the port. it to the port.
3. Accept the Client connection. 3. Now Connection is established.
4. Get the file name and stored into the 4. The object of a BufferedReader class
BufferedReader. is used for storing data content which
5. Create a new object class file and has been retrieved from socket
readLine. object.
6. If file exists then FileReader read the 5. The content of file is displayed in the
content until EOF is reached. client window and the Connection is
7. Stop the program. closed.
6. Stop the program

Program :
FileServer.java
import java.io.*;
import java.net.*;
public class FileServer extends Thread
{
public static final int PORT = 3332;
public static final int BUFFER_SIZE = 100;
@Override
public void run()
{
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server is Ready to Transfer...!");
System.out.println("Waiting...\n");
while (true) {

CS8581 – NETWORKS LABORATORY 25


https://www.ptrcet.org Department of Computer Science and Engineering

Socket s = serverSocket.accept();
saveFile(s);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception
{
ObjectOutputStream oos = new
ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new
ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte [] buffer = new byte[BUFFER_SIZE];
// 1. Read file name.
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream(o.toString());
} else {
throwException("Something is wrong");
}
// 2. Read file to the end.
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException("Something is wrong");
}
bytesRead = (Integer)o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException("Something is wrong");
}
buffer = (byte[])o;
// 3. Write data to output file.
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
System.out.println(" .-----------------------.");
System.out.println(" | File transfer success |");
System.out.println(" .-----------------------.");
fos.close();
ois.close();
oos.close();
System.exit(0);
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new FileServer().start();
}
}
FileClient.java

CS8581 – NETWORKS LABORATORY 26


https://www.ptrcet.org Department of Computer Science and Engineering

import java.io.*;
import java.util.*;
import java.lang.*;
import java.net.*;
public class FileClient
{
public static void main(String[] args) throws Exception
{
String fileName = null;
System.out.println("Connection Established..!\n");
try {
fileName = args[0];
} catch (Exception e)
{
System.out.println("Enter the name of the file :");
Scanner scanner = new Scanner(System.in);
String file_name = scanner.nextLine();
File file = new File(file_name);
Socket socket = new Socket("localhost", 3332);
ObjectInputStream ois = new
ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new
ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte [] buffer = new byte[FileServer.BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
oos.close();
ois.close();
System.exit(0);
}
}
}

Result :

Output : (First run the Server_Program and then run Client_Program)

CS8581 – NETWORKS LABORATORY 27


https://www.ptrcet.org Department of Computer Science and Engineering

(FileServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\FileTransfer>javac
FileServer.java
C:\Users\PTR-PC\Desktop\Computer Networks\FileTransfer>java
FileServer
Server is Ready to Transfer...!
Waiting

.-----------------------.
| File transfer success |
.-----------------------.

(FileClient.java)
C:\Users\PTR-PC\Desktop\Computer Networks\FileTransfer>javac
FileClient.java
C:\Users\PTR-PC\Desktop\Computer Networks\FileTransfer>java
FileClient
Enter the name of the file :
C:\Users\PTR-PC\Desktop\Applications using TCP sockets like Chat.pdf

(Now, the corresponding file store in the location of where the server program is stored.)

CS8581 – NETWORKS LABORATORY 28


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 4

SIMULATION OF DNS USING UDP SOCKETS

Aim :
To write a java program for Simulating DNS using UDP Sockets.

Algorithm :
Server Client

1. Create an array of hosts and its ip 1. Create a datagram socket


address in another array 2. Get domain name from user
2. Create a datagram socket and bind it 3. Create a datagram packet and send
to a port domain name to the server
3. Create a datagram packet to receive 4. Create a datagram packet to receive
client request server message
4. Read the domain name from client to 5. Read server's response
be resolved 6. If ip address then display it else
5. Lookup the host array for the domain display "Domain does not exist"
name 7. Close the client socket
6. If found then retrieve corresponding 8. Stop
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

Program :
UDPdnsServer.java
// 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))

CS8581 – NETWORKS LABORATORY 29


https://www.ptrcet.org Department of Computer Science and Engineering

return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"ptrcet.org","yahoo.com",
"gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"208.91.199.125","68.180.206.184",
"209.85.148.19","80.168.92.140","69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
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();
}
}
}

UDPdnsClient.java
//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;

CS8581 – NETWORKS LABORATORY 30


https://www.ptrcet.org Department of Computer Science and Engineering

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();
}
}

Result :

Output : (First run the Server_Program and then run Client_Program)

CS8581 – NETWORKS LABORATORY 31


https://www.ptrcet.org Department of Computer Science and Engineering

(UDPdnsServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>javac
UDPdnsServer.java
C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>java UDPdnsServer
Press Ctrl + C to Quit
Request for host ptrcet.org
Request for host facebook.com
Request for host youtube.com.com

(UDPdnsClient.java)
C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>javac
UDPdnsClient.java

C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>java UDPdnsClient


Enter the hostname : ptrcet.org
IP Address: 208.91.199.125

C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>java UDPdnsClient


Enter the hostname : facebook.com
IP Address: 69.63.189.16

C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>java UDPdnsClient


Enter the hostname : youtube.com
IP Address: Host Not Found

CS8581 – NETWORKS LABORATORY 32


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 5 (a)

SIMULATING ADDRESS RESOLUTION PROTOCOL (ARP)

Aim :
To write a java program for Simulating Address Resolution Protocol (ARP) using
TCP Sockets.

Algorithm :
Server Client

1. Start the program 1. Start the program


2. Accept the socket which is created by 2. Using socket connection is
the client. established between client and
3. Server maintains the table in which server.
IP and corresponding MAC 3. Get the IP address to be converted
addresses are stored. into MAC address.
4. Send this IP address to server.
4. Read the IP address which is send by 5. Server returns the MAC address to
the client.
client.
5. Map the IP address with its MAC
address and return the MAC address
to client.

Program :
ARPServer.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
class ARPServer
{
public static void main(String args[])
{
System.out.println(" Send IP Address...\n Server is Waiting...\n");
try{
ServerSocket obj=new ServerSocket(1391);
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","192.168.1.1"};

CS8581 – NETWORKS LABORATORY 33


https://www.ptrcet.org Department of Computer Science and Engineering

String mac[]={"6A:08:AA:C2","8A:BC:E3:FA","6E:AD:9D:F5","not
found"};
for(int i=0;i<ip.length;i++){
if(str.equals(ip[i])){
dout.writeBytes(mac[i]+'\n');
System.out.println(" .******************************************.");
System.out.println(" |Successfully Transferred PhysiCAl ADDreSS |");
System.out.println(" .******************************************.");
break;
}
}
dout.writeBytes(mac[3]+'\n');
System.out.println(" .________________.");
System.out.println(" |===INVALID IP===|");
System.out.println(" .________________.");
obj.close();
}
}
catch(Exception e){}
}
}

ARPClient.java
import java.io.*;
import java.net.*;
import java.util.*;
class ARPClient
{
public static void main(String args[])
{
try{
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",1391);
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){}
}
}

Result :

Sample Output 1 : (First run the Server_Program and then run Client_Program)

CS8581 – NETWORKS LABORATORY 34


https://www.ptrcet.org Department of Computer Science and Engineering

(ARPServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\ARP>javac ARPServer.java
C:\Users\PTR-PC\Desktop\Computer Networks\ARP>java ARPServer
Send IP Address...
Server is Waiting...

.******************************************.
|Successfully Transferred PhysiCAl ADDreSS |
.******************************************.

(ARPClient.java)

C:\Users\PTR-PC\Desktop\Computer Networks\ARP>javac ARPClient.java


C:\Users\PTR-PC\Desktop\Computer Networks\ARP>java ARPClient
Enter the Logical address(IP):
192.168.1.1
The Physical Address is: 6E:AD:9D:F5

Sample Output 2 : (First run the Server_Program and then run Client_Program)

(ARPServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\ARP>java ARPServer
Send IP Address...
Server is Waiting...

.________________.
|===INVALID IP===|
.________________.

(ARPClient.java)

C:\Users\PTR-PC\Desktop\Computer Networks\ARP>java ARPClient


Enter the Logical address(IP):
172.169.1.1
The Physical Address is: not found

CS8581 – NETWORKS LABORATORY 35


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 5 (b)

SIMULATING REVERSE ADDRESS RESOLUTION


PROTOCOL (RARP)

Aim :
To write a java program for Simulating Reverse Address Resolution Protocol (RARP)
using UDP Sockets.
Algorithm :
Server Client

1. Start the program. 1. Start the program


2. Server maintains the table in which IP 2. using datagram sockets UDP
and corresponding MAC addresses function is established.
are stored. 3. Get the MAC address to be
3. Read the MAC address which is send converted into IP address.
by the client. 4. end this MAC address to server.
4. Map the IP address with its MAC 5. Server returns the IP address to
address and return the IP address to client.
client.

Program :
RARPServer.java
import java.io.*;
import java.net.*;
import java.util.*;
class RARPServer
{
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();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1","192.168.1.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA","6E:AD:9D:F5"};
for(int i=0;i<ip.length;i++){
if(s.equals(mac[i])){
CS8581 – NETWORKS LABORATORY 36
https://www.ptrcet.org Department of Computer Science and Engineering

sendbyte=ip[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
System.out.println("\n .************************************.");
System.out.println(" |Successfully Transferred IP ADDreSS |");
System.out.println(" .************************************.");
break;
}
}
break;
}
}
catch(Exception e){}
}
}

RARPClient.java
import java.io.*;
import java.net.*;
import java.util.*;
class RARPClient
{
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):");
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){}
}
}

Result :

Sample Output 1 : (First run the Server_Program and then run Client_Program)

CS8581 – NETWORKS LABORATORY 37


https://www.ptrcet.org Department of Computer Science and Engineering

(RARPServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\RARP>javac RARPServer.java

C:\Users\PTR-PC\Desktop\Computer Networks\RARP>java RARPServer

.************************************.
|Successfully Transferred IP ADDreSS |
.************************************.

(ARPClient.java)

C:\Users\PTR-PC\Desktop\Computer Networks\RARP>javac RARPClient.java

C:\Users\PTR-PC\Desktop\Computer Networks\RARP>java RARPClient


Enter the Physical address (MAC):
6E:AD:9D:F5
The Logical Address is(IP):192.168.1.1

Sample Output 2 : (First run the Server_Program and then run Client_Program)

(RARPServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\RARP>javac RARPServer.java

C:\Users\PTR-PC\Desktop\Computer Networks\RARP>java RARPServer

(ARPClient.java)

C:\Users\PTR-PC\Desktop\Computer Networks\RARP>javac RARPClient.java

C:\Users\PTR-PC\Desktop\Computer Networks\RARP>java RARPClient


Enter the Physical address (MAC):
65:AB:C7:BG

CS8581 – NETWORKS LABORATORY 38


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 6

STUDY OF NETWORK SIMULATOR (NS)

Aim :
To study about NS2 simulator in detail.

Theory :

Network Simulator (Version 2), widely known as NS2, is simply an event driven
simulation tool that has proved useful in studying the dynamic nature of communication
networks. Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2. In general, NS2 provides users with a way of
specifying such network protocols and simulating their corresponding behaviors. Due to its
flexibility and modular nature, NS2 has gained constant popularity in the networking research
community since its birth in 1989. Ever since, several revolutions and revisions have marked
the growing maturity of the tool, thanks to substantial contributions from the players in the
field. Among these are the University of California and Cornell University who developed the
REAL network simulator,1 the foundation which NS is based on. Since 1995 the Defense
Advanced Research Projects Agency (DARPA) supported development of NS through the
Virtual Inter Network Testbed (VINT) project. Currently the National Science Foundation
(NSF) has joined the ride in development. Last but not the least, the group of Researchers and
developers in the community are constantly working to keep NS2 strong and versatile.

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
exploring a 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.

CS8581 – NETWORKS LABORATORY 39


https://www.ptrcet.org Department of Computer Science and Engineering

Basic Architecture :

Figure 2.1 shows the basic architecture of NS2. NS2 provides users with an executable
command ns which takes on input argument, the name of a Tcl simulation scripting file. Users
are feeding the name of a Tcl simulation script (which sets up a simulation) as an input
argument of an NS2 executable command ns.

In most cases, a simulation trace file is created, and is used to plot graph and/or to create
animation. NS2 consists of two key languages: C++ and Object-oriented Tool Command
Language (OTcl). While the C++ defines the internal mechanism (i.e., a backend) of the
simulation objects, the OTcl sets up simulation by assembling and configuring the objects as
well as scheduling discrete events (i.e., a frontend).

The C++ and the OTcl are linked together using TclCL. Mapped to a C++
object, variables in the OTcl domains are sometimes referred to as handles. Conceptually, a
handle (e.g., n as a Node handle) is just a string (e.g.,_o10) in the OTcl domain, and does not
contain any functionality. Instead, the functionality (e.g., receiving a packet) is defined in the
mapped C++ object (e.g., of class Connector). In the OTcl domain, a handle acts as a frontend
which interacts with users and other OTcl objects. It may defines its own procedures and variables
to facilitate the interaction. Note that the member procedures and variables in the OTcl domain are
called instance procedures (instprocs) and instance variables (instvars), respectively. Before
proceeding further, the readers are encouraged to learn C++ and OTcl languages. We refer the
readers to [14] for the detail of C++, while a brief tutorial of Tcl and OTcl tutorial are given in
Appendices A.1 and A.2, respectively.

NS2 provides a large number of built-in C++ objects. It is advisable to use these C++
objects to set up a simulation using a Tcl simulation script. However, advance users may find
these objects insufficient. They need to develop their own C++ objects, and use a OTcl
configuration interface to put together these objects. After simulation, NS2 outputs either text-
based or animation-based simulation results. To interpret these results graphically and
interactively, tools such as NAM (Network AniMator) and XGraph are used. To analyze a
particular behaviour of the network, users can extract a relevant subset of text-based data and
transform it to a more conceivable presentation.

CS8581 – NETWORKS LABORATORY 40


https://www.ptrcet.org Department of Computer Science and Engineering

TCL SCRIPTING :
Tcl is a general purpose scripting language. [Interpreter]
 Tcl runs on most of the platforms such as Unix, Windows, and Mac.
 The strength of Tcl is its simplicity.
 It is not necessary to declare a data type for variable prior to the usage.

BASICS OF TCL :
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!} Hello, World!

Variables Command Substitution


set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]

Wired TCL Script Components


Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation

NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.

Initialization and Termination of TCL Script in NS-2


An ns simulation starts with the command
set ns [new Simulator]
Which is thus the first line in the tcl script. This line declares a new variable as using the set
command, you can call this variable as you wish, In general people declares it as ns because
it is an instance of the Simulator class, so an object the code[new Simulator] is indeed the
installation of the class Simulator using the reserved word new.

In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using ―open command:
#Open the Trace file
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile

CS8581 – NETWORKS LABORATORY 41


https://www.ptrcet.org Department of Computer Science and Engineering

The above creates a dta trace file called out.tr and a nam visualization trace file called out.nam.
Within the tcl script, these files are not called explicitly by their names, but instead by pointers
that are declared above and called ―tracefile1 and ―namfile respectively. Remark that they
begins with a # symbol. The second line open the file ―out.tr to be used for writing, declared
with the letter ―w. The third line uses a simulator method called trace-all that have as
parameter the name of the file where the traces will go.

Define a “finish‟ procedure


Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam &
Exit 0
}

Definition of a network of links and nodes


The way to define a node is
set n0 [$ns node]
Once we define several nodes, we can define the links that connect them. An example of a
definition of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction.

To define a directional link instead of a bi-directional one, we should replace ―duplex-link


by ―simplex-link.
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example
would be:
#set Queue Size of link (n0-n2) to 20
$ns queue-limit $n0 $n2 20

FTP over TCP


TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements created by
the destination to know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas. The
type of agent appears in the first line:

set tcp [new Agent/TCP]

The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command set sink [new Agent /TCPSink] Defines the behavior of the destination node
of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null

CS8581 – NETWORKS LABORATORY 42


https://www.ptrcet.org Department of Computer Science and Engineering

$ns connect $udp $null


$udp set fid_2

#setup a CBR over UDP connection


The below shows the definition of a CBR application using a UDP agent
The command $ns attach-agent $n4 $sink defines the destination node. The command $ns
connect $tcp $sink finally makes the TCP connection between the source and destination
nodes.

set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp
$cbr set packetsize_ 100
$cbr set rate_ 0.01Mb
$cbr set random_ false

TCP has many parameters with initial fixed defaults values that can be changed if mentioned
explicitly. For example, the default TCP packet size has a size of 1000bytes.This can be
changed to another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify them
with different colors in the visualization part. This is done by the command $tcp set fid_ 1 that
assigns to the TCP connection a flow identification of ―1.We shall later give the flow
identification of ―2‖ to the UDP connection.

Result :

CS8581 – NETWORKS LABORATORY 43


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 7

STUDY OF TCP / UDP PERFORMANCE USING


SIMULATION TOOL

Aim :
To study TCP / UDP performance using simulaton tool.

CASE STUDY – 1 TCP


The transmission Control Protocol (TCP) is one of the most important protocols of Internet
Protocols suite. It is most widely used protocol for data transmission in communication
network such as internet.

Features
• TCP is reliable protocol. That is, the receiver always sends either positive or negative
acknowledgement about the data packet to the sender, so that the sender always has
bright clue about whether the data packet is reached the destination or it needs to resend
it.
• TCP ensures that the data reaches intended destination in the same order it was sent.
• TCP is connection oriented. TCP requires that connection between two remote points
be established before sending actual data.
• TCP provides error-checking and recovery mechanism.
• TCP provides end-to-end communication.
• TCP provides flow control and quality of service.
• TCP operates in Client/Server point-to-point mode.
• TCP provides full duplex server, i.e. it can perform roles of both receiver and sender.

Header

The length of TCP header is minimum 20 bytes long and maximum 60 bytes.

CS8581 – NETWORKS LABORATORY 44


https://www.ptrcet.org Department of Computer Science and Engineering

• Source Port (16-bits) - It identifies source port of the application process on the
sending device.
• Destination Port (16-bits) - It identifies destination port of the application process on
the receiving device.
• Sequence Number (32-bits) - Sequence number of data bytes of a segment in a session.
• Acknowledgement Number (32-bits) - When ACK flag is set, this number contains
the next sequence number of the data byte expected and works as acknowledgement of
the previous data received.
• Data Offset (4-bits) - This field implies both, the size of TCP header (32-bit words)
and the offset of data in current packet in the whole TCP segment.
• Reserved (3-bits) - Reserved for future use and all are set zero by default.
• Flags (1-bit each) o NS - Nonce Sum bit is used by Explicit Congestion Notification
signaling process.
 CWR - When a host receives packet with ECE bit set, it sets Congestion
Windows Reduced to acknowledge that ECE received.
 ECE -It has two meanings:
 If SYN bit is clear to 0, then ECE means that the IP packet has its CE
(congestion experience) bit set.
 If SYN bit is set to 1, ECE means that the device is ECT capable.
 URG - It indicates that Urgent Pointer field has significant data and
should be processed.
 ACK - It indicates that Acknowledgement field has significance. If
ACK is cleared to 0, it indicates that packet does not contain any
acknowledgement.
 PSH - When set, it is a request to the receiving station to PUSH data (as
soon as it comes) to the receiving application without buffering it. o RST - Reset
flag has the following features:
 It is used to refuse an incoming connection.
 It is used to reject a segment.
 It is used to restart a connection.
 SYN - This flag is used to set up a connection between hosts.
 FIN - This flag is used to release a connection and no more data is
exchanged thereafter. Because packets with SYN and FIN flags have sequence
numbers, they are processed in correct order.
• Windows Size - This field is used for flow control between two stations and indicates
the amount of buffer (in bytes) the receiver has allocated for a segment, i.e. how much
data is the receiver expecting.
• Checksum - This field contains the checksum of Header, Data and Pseudo Headers.
• Urgent Pointer - It points to the urgent data byte if URG flag is set to 1.
• Options - It facilitates additional options which are not covered by the regular header.
Option field is always described in 32-bit words. If this field contains data less than 32-
bit, padding is used to cover the remaining bits to reach 32-bit boundary.

Addressing

CS8581 – NETWORKS LABORATORY 45


https://www.ptrcet.org Department of Computer Science and Engineering

TCP communication between two remote hosts is done by means of port numbers (TSAPs).
Ports numbers can range from 0 – 65535 which are divided as:
 System Ports (0 – 1023)
 User Ports (1024 – 49151)
 Private Dynamic Ports (49152 – 65535)

Connection Management
TCP communication works in Server/Client model. The client initiates the connection and the
server either accepts or rejects it. Three-way handshaking is used for connection management.

Establishment
Client initiates the connection and sends the segment with a Sequence number. 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.

Release
Either of server and client can send TCP segment with FIN flag set to 1. When the receiving
end responds it back by ACKnowledging FIN, that direction of TCP communication is closed
and connection is released.

Bandwidth Management
TCP uses the concept of window size to accommodate the need of Bandwidth management.
Window size tells the sender at the remote end, the number of data byte segments the receiver
at this end can receive. TCP uses slow start phase by using window size 1 and increases the
window size exponentially after each successful communication.

CS8581 – NETWORKS LABORATORY 46


https://www.ptrcet.org Department of Computer Science and Engineering

For example, the client uses windows size 2 and sends 2 bytes of data. When the
acknowledgement of this segment received the windows size is doubled to 4 and next sent the
segment sent will be 4 data bytes long. When the acknowledgement of 4-byte data segment is
received, the client sets windows size to 8 and so on.
If an acknowledgement is missed, i.e. data lost in transit network or it received NACK, then
the window size is reduced to half and slow start phase starts again.

Error Control &and Flow Control


TCP uses port numbers to know what application process it needs to handover the
data segment. Along with that, it uses sequence numbers to synchronize itself with the remote
host. All data segments are sent and received with sequence numbers. The Sender knows
which last data segment was received by the Receiver when it gets ACK. The Receiver
knows about the last segment sent by the Sender by referring to the sequence number of
recently received packet.

If the sequence number of a segment recently received does not match with the
sequence number the receiver was expecting, then it is discarded and NACK is sent back. If
two segments arrive with the same sequence number, the TCP timestamp value is compared
to make a decision.

Multiplexing
The technique to combine two or more data streams in one session is called
Multiplexing. When a TCP client initializes a connection with Server, it always refers to a
well-defined port number which indicates the application process. The client itself uses a
randomly generated port number from private port number pools.

Using TCP Multiplexing, a client can communicate with a number of different


application process in a single session. For example, a client requests a web page which in
turn contains different types of data (HTTP, SMTP, FTP etc.) the TCP session timeout is
increased and the session is kept open for longer time so that the three-way handshake
overhead can be avoided.

This enables the client system to receive multiple connection over single virtual
connection. These virtual connections are not good for Servers if the timeout is too long.

Congestion Control
When large amount of data is fed to system which is not capable of handling it, congestion
occurs. TCP controls congestion by means of Window mechanism. TCP sets a window size
telling the other end how much data segment to send. TCP may use three algorithms for
congestion control:
 Additive increase, Multiplicative Decrease
 Slow Start
 Timeout React

Timer Management
TCP uses different types of timer to control and management various tasks:
CS8581 – NETWORKS LABORATORY 47
https://www.ptrcet.org Department of Computer Science and Engineering

Keep-alive timer:
 This timer is used to check the integrity and validity of a connection.
 When keep-alive time expires, the host sends a probe to check if the connection still
exists.
Retransmission timer:
 This timer maintains stateful session of data sent.
 If the acknowledgement of sent data does not receive within the Retransmission time,
the data segment is sent again.
Persist timer:
 TCP session can be paused by either host by sending Window Size 0.
 To resume the session a host needs to send Window Size with some larger value.
 If this segment never reaches the other end, both ends may wait for each other for
infinite time.
 When the Persist timer expires, the host re-sends its window size to let the other end
know.
 Persist Timer helps avoid deadlocks in communication.
Timed-Wait:
 After releasing a connection, either of the hosts waits for a Timed-Wait time to
terminate the connection completely.
 This is in order to make sure that the other end has received the acknowledgement of
its connection termination request.
 Timed-out can be a maximum of 240 seconds (4 minutes).

Crash Recovery
TCP is very reliable protocol. It provides sequence number to each of byte sent in segment. It
provides the feedback mechanism i.e. when a host receives a packet, it is bound to ACK that
packet having the next sequence number expected (if it is not the last segment).
When a TCP Server crashes mid-way communication and re-starts its process it sends TPDU
broadcast to all its hosts. The hosts can then send the last data segment which was never
unacknowledged and carry onwards.

CASE STUDY – 2 UDP


The User Datagram Protocol (UDP) is simplest Transport Layer communication
protocol available of the TCP/IP protocol suite. It involves minimum amount of

CS8581 – NETWORKS LABORATORY 48


https://www.ptrcet.org Department of Computer Science and Engineering

communication mechanism. UDP is said to be an unreliable transport protocol but it uses IP


services which provides best effort delivery mechanism.
In UDP, the receiver does not generate an acknowledgement of packet received and in
turn, the sender does not wait for any acknowledgement of packet sent. This shortcoming
makes this protocol unreliable as well as easier on processing.
Requirement of UDP
A question may arise, why do we need an unreliable protocol to transport the data? We
deploy UDP where the acknowledgement packets share significant amount of bandwidth along
with the actual data. For example, in case of video streaming, thousands of packets are
forwarded towards its users. Acknowledging all the packets is troublesome and may contain
huge amount of bandwidth wastage. The best delivery mechanism of underlying IP protocol
ensures best efforts to deliver its packets, but even if some packets in video streaming get lost,
the impact is not calamitous and can be ignored easily. Loss of few packets in video and voice
traffic sometimes goes unnoticed.

Features
 UDP is used when acknowledgement of data does not hold any significance. UDP is
good protocol for data flowing in one direction.
 UDP is simple and suitable for query based communications.
 UDP is not connection oriented.
 UDP does not provide congestion control mechanism.
 UDP does not guarantee ordered delivery of data.
 UDP is stateless.
 UDP is suitable protocol for streaming applications such as VoIP, multimedia
streaming.

UDP Header
UDP header is as simple as its function.

UDP header contains four main parameters:


 Source Port - This 16 bits information is used to identify the source port of the
packet.

CS8581 – NETWORKS LABORATORY 49


https://www.ptrcet.org Department of Computer Science and Engineering

 Destination Port - This 16 bits information, is used identify application level service
on destination machine.
 Length - Length field specifies the entire length of UDP packet (including header). It
is 16bits field and minimum value is 8-byte, i.e. the size of UDP header itself.
 Checksum - This field stores the checksum value generated by the sender before
sending. IPv4 has this field as optional so when checksum field does not contain any
value it is made 0 and all its bits are set to zero.

UDP application
Here are few applications where UDP is used to transmit data:
 Domain Name Services
 Simple Network Management Protocol
 Trivial File Transfer Protocol
 Routing Information Protocol
 Kerberos

Result :

CS8581 – NETWORKS LABORATORY 50


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 8 (a)

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 :

CS8581 – NETWORKS LABORATORY 51


https://www.ptrcet.org Department of Computer Science and Engineering

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 }

$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]


CS8581 – NETWORKS LABORATORY 52
https://www.ptrcet.org Department of Computer Science and Engineering

$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

Result :

CS8581 – NETWORKS LABORATORY 53


https://www.ptrcet.org Department of Computer Science and Engineering

Output :

CS8581 – NETWORKS LABORATORY 54


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 8 (b)

SIMULATION OF LINK STATE ROUTING 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

CS8581 – NETWORKS LABORATORY 55


https://www.ptrcet.org Department of Computer Science and Engineering

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
}

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

CS8581 – NETWORKS LABORATORY 56


https://www.ptrcet.org Department of Computer Science and Engineering

$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

Result :

CS8581 – NETWORKS LABORATORY 57


https://www.ptrcet.org Department of Computer Science and Engineering

Output :

CS8581 – NETWORKS LABORATORY 58


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 9

PERFORMANCE EVALUATION OF ROUTING


PROTOCOLS

Aim :
To create scenario and study the performance of CSMA / CA and CSMA / CD protocol
through simulation.

Software Required :
 NS-2

Theory :

Ethernet is a LAN (Local area Network) protocol operating at the MAC (Medium
Access Control) layer. Ethernet has been standardized as per IEEE 802.3. The underlying
protocol in Ethernet is known as the CSMA / CD – Carrier Sense Multiple Access / Collision
Detection. The working of the Ethernet protocol is as explained below, A node which has data
to transmit senses the channel. If the channel is idle then, the data is transmitted. If the channel
is busy then, the station defers transmission until the channel is sensed to be idle and then
immediately transmitted. If more than one node starts data transmission at the same time, the
data collides. This collision is heard by the transmitting nodes which enter into contention
phase. The contending nodes resolve contention using an algorithm called Truncated binary
exponential back off.

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 six nodes that forms a network numbered from 0 to 5
5. Create duplex links between the nodes and add Orientation to the nodes for setting a
LAN topology
6. Setup TCP Connection between n(0) and n(4)
7. Apply FTP Traffic over TCP
8. Setup UDP Connection between n(1) and n(5)
9. Apply CBR Traffic over UDP.
10. Apply CSMA/CA and CSMA/CD mechanisms and study their performance
11. Schedule events and run the program.

CS8581 – NETWORKS LABORATORY 59


https://www.ptrcet.org Department of Computer Science and Engineering

Program :
CSMA / CA

set ns [new Simulator]


#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace files
set file1 [open out.tr w]
set winfile [open WinFile w]
$ns trace-all $file1
#Open the NAM trace file
set file2 [open out.nam w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit 0
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n1 color red
$n1 shape box
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Ca
Channel]
Setup a TCP connection
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
CS8581 – NETWORKS LABORATORY 60
https://www.ptrcet.org Department of Computer Science and Engineering

$tcp set fid_ 1


$tcp set window_ 8000
$tcp set packetSize_ 552
#Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_ 2
#Setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 0.01mb
$cbr set random_ false
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"
# next procedure gets two arguments: the name of the
# tcp source node, will be called here "tcp",
# and the name of output file.
proc plotWindow {tcpSource file} {
global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
set wnd [$tcpSource set window_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 0.1 "plotWindow $tcp $winfile"
$ns at 5 "$ns trace-annotate \"packet drop\""
# PPP
$ns at 125.0 "finish"
$ns run

CSMA / CD

CS8581 – NETWORKS LABORATORY 61


https://www.ptrcet.org Department of Computer Science and Engineering

set ns [new Simulator]


#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace files
set file1 [open out.tr w]
set winfile [open WinFile w]
$ns trace-all $file1
#Open the NAM trace file
set file2 [open out.nam w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit 0
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n1 color red
$n1 shape box
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd
Channel]
Setup a TCP connection
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetSize_ 552

CS8581 – NETWORKS LABORATORY 62


https://www.ptrcet.org Department of Computer Science and Engineering

#Setup a FTP over TCP connection


set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_ 2
#Setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 0.01mb
$cbr set random_ false
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"
# next procedure gets two arguments: the name of the
# tcp source node, will be called here "tcp",
# and the name of output file.
proc plotWindow {tcpSource file} {
global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
set wnd [$tcpSource set window_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 0.1 "plotWindow $tcp $winfile"
$ns at 5 "$ns trace-annotate \"packet drop\""
# PPP
$ns at 125.0 "finish"
$ns run

Result :

CS8581 – NETWORKS LABORATORY 63


https://www.ptrcet.org Department of Computer Science and Engineering

Output : (CSMA / CA)

Output : (CSMA / CD)

SIMULATION OF ERROR CORRECTION CODE (LIKE CRC)

CS8581 – NETWORKS LABORATORY 64


https://www.ptrcet.org Department of Computer Science and Engineering

Date : Expt. No. 10

SIMULATION OF ERROR CORRECTION CODE (LIKE CRC)

Aim :
To write a java program to find CRC of a given number.

Theory:
The upper layers work on some generalized view of network architecture and are not
aware of actual hardware data processing. Hence, the upper layers expect error-free
transmission between the systems. Most of the applications would not function expectedly if
they receive erroneous data. Applications such as voice and video may not be that affected
and with some errors they may still function well. Data-link layer uses some error control
mechanism to ensure that frames (data bit streams) are transmitted with certain level of
accuracy. But to understand how errors is controlled, it is essential to know what types of
errors may occur. CRC is a different approach to detect if the received frame contains valid
data. This technique involves binary division of the data bits being sent. The divisor is
generated using polynomials. The sender performs a division operation on the bits being sent
and calculates the remainder. Before sending the actual bits, the sender adds the remainder at
the end of the actual bits. Actual data bits plus the remainder is called a codeword. The sender
transmits data bits as codewords.

Algorithm :

1. Get the input in the form of bits.


2. Append 16 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 9. Run the program.

Program :
CS8581 – NETWORKS LABORATORY 65
https://www.ptrcet.org Department of Computer Science and Engineering

import java.io.*;
import java.util.*;
class CRC
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
//Input Data Stream
System.out.println("Enter Data Stream :");
String datastream=sc.nextLine();
System.out.println("Enter generator :");
String generator=sc.nextLine();
int data[]=new int[datastream.length() + generator.length() -
1];
int divisor[]=new int[generator.length()];
for(int i=0;i<datastream.length();i++)
data[i]=Integer.parseInt(datastream.charAt(i)+"");
for(int i=0;i<generator.length();i++)
divisor[i]=Integer.parseInt(generator.charAt(i)+"");

//Calculation of CRC
for(int i=0;i<datastream.length();i++)
{
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j]^=divisor[j];
}

//Display CRC
System.out.println("The CRC Code is :");
for(int i=0;i<datastream.length();i++)
data[i]=Integer.parseInt(datastream.charAt(i)+"");
for(int i=0;i<data.length;i++)
System.out.print(data[i]);
System.out.println();

//Check for input CRC code


System.out.println("\nEnter CRC Code :");
datastream=sc.nextLine();
System.out.println("Enter generator :");
generator=sc.nextLine();
data=new int[datastream.length() + generator.length() -1];
divisor=new int[generator.length()];
for(int i=0;i<datastream.length();i++)
data[i]=Integer.parseInt(datastream.charAt(i)+"");

CS8581 – NETWORKS LABORATORY 66


https://www.ptrcet.org Department of Computer Science and Engineering

for(int i=0;i<generator.length();i++)
divisor[i]=Integer.parseInt(generator.charAt(i)+"");

//Calculation of Remainder
for(int i=0;i<datastream.length();i++)
{
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j]^=divisor[j];
}

//Display validity of data


boolean valid=true;
for(int i=0;i<data.length;i++)
if(data[i]==1)
{
valid=false;
break;
}

if(valid==true)
System.out.println("Data stream is valid");
else
System.out.println("Data stream is invalid. CRC error
occured...!");
}
}

Result :

CS8581 – NETWORKS LABORATORY 67


https://www.ptrcet.org Department of Computer Science and Engineering

Sample Output 1 :

C:\Users\PTR-PC\Desktop\Computer Networks>javac CRC.java

C:\Users\PTR-PC\Desktop\Computer Networks>java CRC


Enter Data Stream :
101010
Enter generator :
11111
The CRC Code is :
1010101010

Enter CRC Code :


1010101010
Enter generator :
11111
Data stream is valid

Sample Output 2 :

C:\Users\PTR-PC\Desktop\Computer Networks>java CRC


Enter Data Stream :
101010
Enter generator :
11111
The CRC Code is :
1010101010

Enter CRC Code :


1010100010
Enter generator :
11111
Data stream is invalid. CRC error occured...!

CS8581 – NETWORKS LABORATORY 68

You might also like