0% found this document useful (0 votes)
19 views61 pages

22CS501 CN Lab Manual

The document is a lab manual for the Computer Networks course at R.M.D. Engineering College for the academic year 2024-25. It outlines the objectives, exercises, and expected outcomes for students, focusing on network commands, error detection, flow control, and protocol simulations. The manual includes practical exercises using various tools and commands in Windows and Linux operating systems to enhance students' understanding of computer networking concepts.

Uploaded by

oopsitsmysteria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views61 pages

22CS501 CN Lab Manual

The document is a lab manual for the Computer Networks course at R.M.D. Engineering College for the academic year 2024-25. It outlines the objectives, exercises, and expected outcomes for students, focusing on network commands, error detection, flow control, and protocol simulations. The manual includes practical exercises using various tools and commands in Windows and Linux operating systems to enhance students' understanding of computer networking concepts.

Uploaded by

oopsitsmysteria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

R.M.D.

ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

22CS501
COMPUTER NETWORKS
(Lab Integrated)

LAB MANUAL

ACADEMIC YEAR: 2024-25

ODD SEMESTER

B.E. COMPUTER SCIENCE AND ENGINEERING

ANNA UNIVERSITY - CHENNAI


R.M.D. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

22CS501-COMPUTER NETWORKS (Lab Integrated)

OBJECTIVES:
 To explore various network commands in different Operating Systems and troubleshoot it.
 To implement the error detection & correction and flow control mechanisms in network data
communication.
 To implement functionalities using raw sockets.
 To understand and implement the network programming concepts using APIs.
 To simulate various network protocols and analyze their behaviour in the network
LIST OF EXERCISES:
1. Practice different network commands available in Windows and Linux Operating
Systems and troubleshoot the network.
2. Network configuration commands using Linux.
3. Error detection and correction mechanisms.
4. Flow control mechanisms.
5. Multi-client chatting in TCP and UDP using Socket programming ( C / Java)
6. Implementation of HTTP, Web Caching, FTP using socket programming.
7. Develop a DNS client server to resolve the given host name or IP address.
8. Simulation of unicast routing protocols.
9. Observing Packets across the network and Performance Analysis of various Routing
protocols.
10. Simulation of Transport layer Protocols and analysis of congestion control techniques in
the network.

OUTCOMES:
At the end of this course, the students will be able to:
CO1: Understand the various networking commands in different OS and troubleshoot it.
CO2: Perform error detection & correction and flow control mechanisms in network programming.
CO3: Program with raw sockets for network protocol implementation.
CO4: Understand the usage of various network programming APIs and application layer protocols.
CO5: Simulate various network protocols and analyze their behavior in the network
R.M.D. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

INDEX

Sl. No. Name of the Exercise


1. Practice different network commands available in Windows and Linux Operating
Systems and troubleshoot the network.
2. Network configuration commands using Linux.
3. Error detection and correction mechanisms.
4. Flow control mechanisms.
5. Multi-client chatting in TCP and UDP using Socket programming ( C / Java)
6. Implementation of HTTP, Web Caching, FTP using socket programming.
7. Develop a DNS client server to resolve the given host name or IP address.
8. Simulation of unicast routing protocols.
9. Observing Packets across the network and Performance Analysis of various
Routing protocols.
10. Simulation of Transport layer Protocols and analysis of congestion control
techniques in the network.
Content beyond the Syllabus

11 Simulation of Link State Routing using Dijkstra's Algorithm


EX.NO:1 Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute.
Capture ping and traceroute PDUs using a network protocol analyzer and examine.

AIM: To Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute ping.

PRE LAB DISCUSSION:

Tcpdump:
The tcpdump utility allows you to capture packets that flow within your network to assist in
network troubleshooting. The following are several examples of using tcpdump with different options.
Traffic is captured based on a specified filter.
Netstat
Netstat is a common command line TCP/IP networking 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.
ipconfig
ipconfig is a console application designed to run from the Windows command prompt. This
utility allows you to get the IP address information of a Windows computer.
From the command prompt, type ipconfig to run the utility with default options. The output of the
default command contains the IP address, network mask, and gateway for all physical and virtual
network adapter.
nslookup
The nslookup (which stands for name server lookup) command is a network utility program used
to obtain information about internet servers. It finds name server information for domains by querying
the Domain Name System.
Trace route:
Traceroute is a network diagnostic tool used to track the pathway taken by a packet on an IP
network from source to destination. Traceroute also records the time taken for each hop the packet
makes during its route to the destination

Commands:
Tcpdump:
Display traffic between 2 hosts:
To display all traffic between two hosts (represented by variables host1 and host2): # tcpdump
host host1 and host2
Display traffic from a source or destination host only:
To display traffic from only a source (src) or destination (dst)
host: # tcpdump src host
# tcpdump dst host
Display traffic for a specific protocol
Provide the protocol as an argument to display only traffic for a specific protocol, for example tcp,
udp, icmp, arp
# tcpdump protocol
For example to display traffic only for the tcp traffic :
# tcpdump tcp
Filtering based on source or destination port
To filter based on a source or destination port:
# tcpdump src port ftp
# tcpdump dst port
http

2. Netstat
Netstat is a common command line TCP/IP networking 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. The Windows help screen (analogous to a Linux or UNIX for netstat reads as follows:
displays protocol statistics and current TCP/IP network connections.

#netstat

3. ipconfig

In Windows, ipconfig is a console application designed to run from the Windows command
prompt. This utility allows you to get the IP address information of a Windows computer.
Using ipconfig
From the command prompt, type ipconfig to run the utility with default options. The output of the
default command contains the IP address, network mask, and gateway for all physical and virtual
network adapter.

#ipconfig
4. nslookup
The nslookup (which stands for name server lookup) command is a network utility program used
to obtain information about internet servers. It finds name server information for domains by querying
the Domain Name System.

The nslookup command is a powerful tool for diagnosing DNS problems. You know you're
experiencing a DNS problem when you can access a resource by specifying its IP address but not its
DNS name.

#nslookup

5. Trace route:

Traceroute uses Internet Control Message Protocol (ICMP) echo packets with variable time to live
(TTL) values. The response time of each hop is calculated. To guarantee accuracy, each hop is queried
multiple times (usually three times) to better measure the response of that particular hop.
Traceroute is a network diagnostic tool used to track the pathway taken by a packet on an IP network
from source to destination. Traceroute also records the time taken for each hop the packet makes
during its route to the destination. Traceroute uses Internet Control Message Protocol (ICMP) echo
packets with variable time to live (TTL) values.
The response time of each hop is calculated. To guarantee accuracy, each hop is queried
multiple times (usually three times) to better measure the response of that particular hop. Traceroute
sends packets with TTL values that gradually increase from packet to packet, starting with TTL value
of one. Routers decrement TTL values of packets by one when routing and discard packets whose
TTLvalue has reached zero, returning the ICMP error message ICMP Time Exceeded.

For the first set of packets, the first router receives the packet, decrements the TTL value and
drops the packet because it then has TTL value zero. The router sends an ICMP Time Exceeded
message back to the source. The next set of packets are given a TTL value of two, so the first router
forwards the packets, but the second router drops them and replies with ICMP Time Exceeded.
Proceeding in this way, traceroute uses the returned ICMP Time Exceeded messages to build a list of
routers that packets traverse, until the destination is reached and returns an ICMP Echo Reply
message.

With the tracert command shown above, we're asking tracert to show us the path from the local
computer all the way to the network device with the hostname

www.google.com.

#tracert google.com

6. Ping:
The ping command sends an echo request to a host available on the network. Using this command,
you can check if your remote host is responding well or not. Tracking and isolating hardware and
software problems. Determining the status of the network and various foreign hosts. The ping
command is usually used as a simple way to verify that a computer can communicate over the
networkwith 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

# ping172.16.6.2
RESULT:
Thus the various networks commands like tcpdump, netstat, ifconfig,
nslookup and tracerouteping are executed successfully.
EX.NO:2 Learn to use Network configuration commands using Linux.

AIM: To Learn to use Network configuration commands using Linux.

1. ifconfig Command

ifconfig (interface configurator) command is used to initialize an interface, assign IP Address to


interface and enable or disable interface on demand.
With this command, you can view IP Address and Hardware / MAC address assign to interface
and also MTU (Maximum transmission unit) size.

# ifconfig

eth0 Link encap:Ethernet HWaddr 00:0C:29:28:FD:4C


inet addr:192.168.50.2 Bcast:192.168.50.255
Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe28:fd4c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:6093 errors:0 dropped:0 overruns:0
frame:0
TX packets:4824 errors:0 dropped:0 overruns:0
carrier:0
collisions:0 txqueuelen:1000
RX bytes:6125302 (5.8 MiB) TX bytes:536966 (524.3
KiB)
Interrupt:18 Base address:0x2000

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:16436 Metric:1
RX packets:8 errors:0 dropped:0 overruns:0 frame:0
TX packets:8 errors:0 dropped:0 overruns:0
carrier:0
collisions:0 txqueuelen:0
RX bytes:480 (480.0 b) TX bytes:480 (480.0 b)

2. Ping Command

Ping (Packet INternet Groper) command is the best way to test connectivity between
two nodes. Whether it is Local Area Network (LAN) or Wide AreaNetwork (WAN).

Ping uses ICMP (Internet Control Message Protocol) to communicate to other devices.
You can ping hostname or ip address using the below commands.
# ping 4.2.2.2

PING 4.2.2.2 (4.2.2.2) 56(84) bytes of data.


64 bytes from 4.2.2.2: icmp_seq=1 ttl=44 time=203 ms
64 bytes from 4.2.2.2: icmp_seq=2 ttl=44 time=201 ms
64 bytes from 4.2.2.2: icmp_seq=3 ttl=44 time=201 ms

OR

# ping www.tecmint.com

PING tecmint.com (50.116.66.136) 56(84) bytes of data.


64 bytes from 50.116.66.136: icmp_seq=1 ttl=47 time=284 ms
64 bytes from 50.116.66.136: icmp_seq=2 ttl=47 time=287 ms
64 bytes from 50.116.66.136: icmp_seq=3 ttl=47 time=285 ms

3. Traceroute Command

traceroute is a network troubleshooting utility that shows the number of hops taken to
reach a destination also determines packets traveling path. Below we are tracing the
route to the global DNS server IP Address and able to reach destination also shows the
path of that packet is traveling.

# traceroute 4.2.2.2

traceroute to 4.2.2.2 (4.2.2.2), 30 hops max, 60 byte


packets
1 192.168.50.1 (192.168.50.1) 0.217 ms 0.624 ms 0.133
ms
2 227.18.106.27.mysipl.com (27.106.18.227) 2.343 ms
1.910 ms 1.799 ms
3 221-231-119-111.mysipl.com (111.119.231.221) 4.334 ms
4.001 ms 5.619 ms
4 10.0.0.5 (10.0.0.5) 5.386 ms 6.490 ms 6.224 ms
5 gi0-0-0.dgw1.bom2.pacific.net.in (203.123.129.25) 7.798
ms 7.614 ms 7.378 ms
6 115.113.165.49.static-mumbai.vsnl.net.in
(115.113.165.49) 10.852 ms 5.389 ms 4.322 ms
7 ix-0-100.tcore1.MLV-Mumbai.as6453.net (180.87.38.5)
5.836 ms 5.590 ms 5.503 ms
8 if-9-5.tcore1.WYN-Marseille.as6453.net (80.231.217.17)
216.909 ms 198.864 ms 201.737 ms
9 if-2-2.tcore2.WYN-Marseille.as6453.net (80.231.217.2)
203.305 ms 203.141 ms 202.888 ms
10 if-5-2.tcore1.WV6-Madrid.as6453.net (80.231.200.6)
200.552 ms 202.463 ms 202.222 ms
11 if-8-2.tcore2.SV8-Highbridge.as6453.net (80.231.91.26)
205.446 ms 215.885 ms 202.867 ms
12 if-2-2.tcore1.SV8-Highbridge.as6453.net (80.231.139.2)
202.675 ms 201.540 ms 203.972 ms
13 if-6-2.tcore1.NJY-Newark.as6453.net (80.231.138.18)
203.732 ms 203.496 ms 202.951 ms
14 if-2-2.tcore2.NJY-Newark.as6453.net (66.198.70.2)
203.858 ms 203.373 ms 203.208 ms
15 66.198.111.26 (66.198.111.26) 201.093 ms 63.243.128.25
(63.243.128.25) 206.597 ms 66.198.111.26 (66.198.111.26)
204.178 ms
16 ae9.edge1.NewYork.Level3.net (4.68.62.185) 205.960 ms
205.740 ms 205.487 ms
17 vlan51.ebr1.NewYork2.Level3.net (4.69.138.222) 203.867
ms vlan52.ebr2.NewYork2.Level3.net (4.69.138.254) 202.850
ms vlan51.ebr1.NewYork2.Level3.net (4.69.138.222) 202.351
ms
18 ae-6-6.ebr2.NewYork1.Level3.net (4.69.141.21) 201.771
ms 201.185 ms 201.120 ms
19 ae-81-81.csw3.NewYork1.Level3.net (4.69.134.74) 202.407
ms 201.479 ms ae-92-92.csw4.NewYork1.Level3.net
(4.69.148.46) 208.145 ms
20 ae-2-70.edge2.NewYork1.Level3.net (4.69.155.80) 200.572
ms ae-4-90.edge2.NewYork1.Level3.net (4.69.155.208) 200.402
ms ae-1-60.edge2.NewYork1.Level3.net (4.69.155.16) 203.573
ms
21 b.resolvers.Level3.net (4.2.2.2) 199.725 ms 199.190 ms
202.488 ms

4. Netstat Command

Netstat (Network Statistic) command displays connection info, routing table


information, etc. To display routing table information use option as -r.

# netstat -r

Kernel IP routing table


Destination Gateway Genmask Flags MSS
Window irtt Iface
192.168.50.0 * 255.255.255.0 U 0
0 0 eth0
link-local * 255.255.0.0 U 0
0 0 eth0
default 192.168.50.1 0.0.0.0 UG 0
0 0 eth0
5. Dig Command

Dig (domain information groper) query DNS related information


like A Record, CNAME, MX Record, etc. This command is mainly used to
troubleshoot DNS-related queries.

# dig www.tecmint.com; <<>> DiG 9.8.2rc1-RedHat-9.8.2-


0.10.rc1.el6 <<>> www.tecmint.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<

6. Nslookup Command

nslookup command is also used to find out DNS-related queries. The following
examples show A Record (IP Address) of tecmint.com.

# nslookup www.tecmint.com
Server: 4.2.2.2
Address: 4.2 2.2#53

Non-authoritative answer:
www.tecmint.com canonical name = tecmint.com.
Name: tecmint.com
Address: 50.116.66.136

7. Route Command

route command also shows and manipulates the ip routing table. To see the default
routing table in Linux, type the following command.

# route

Kernel IP routing table


Destination Gateway Genmask Flags Metric
Ref Use Iface
192.168.50.0 * 255.255.255.0 U 0
0 0 eth0
link-local * 255.255.0.0 U 1002
0 0 eth0
default 192.168.50.1 0.0.0.0 UG 0
0 0 eth0
8. Host Command

host command to find a name to IP or IP to name in IPv4 or IPv6 and also


query DNS records.

# host www.google.com

www.google.com has address 173.194.38.180


www.google.com has address 173.194.38.176
www.google.com has address 173.194.38.177
www.google.com has address 173.194.38.178
www.google.com has address 173.194.38.179
www.google.com has IPv6 address 2404:6800:4003:802::1014

9. Arp Command

ARP (Address Resolution Protocol) is useful to view/add the contents of the


kernel’s ARP tables. To see the default table use the command as.

# arp -e

Address HWtype HWaddress Flags


Mask Iface
192.168.50.1 ether 00:50:56:c0:00:08 C
eth0

10. Ethtool Command

ethtool is a replacement for mii-tool. It is to view, setting speed and duplex of


your Network Interface Card (NIC). You can set duplex permanently
in /etc/sysconfig/network-scripts/ifcfg-eth0 with ETHTOOL_OPTS variable.

# ethtool eth0

Settings for eth0:


Current message level: 0x00000007 (7)
Link detected: yes

11. Iwconfig Command

iwconfig command in Linux is used to configure a wireless network interface. You


can see and set the basic Wi-Fi details like SSID channel and encryption. You can refer
man page of iwconfig to know more.
# iwconfig [interface]

12. Hostname Command

The hostname is to identify in a network. Execute the hostname command to see the
hostname of your box. You can set hostname permanently in /etc/sysconfig/network.
Need to reboot box once set a proper hostname.

# hostname

tecmint.com

RESULT:
Thus the various networks configuration commands are executed successfully.
EX.NO 3 Simulation of Error Correction Code(CRC)

AIM :
To Simulation of Error Correction Code using Java.

Theory:

Cyclic redundancy check (CRC)

 Unlike checksum scheme, which is based on addition, CRC is based on binary


division.
 In CRC, a sequence of redundant bits, called cyclic redundancy check bits, are
appended to the end of data unit so that the resulting data unit becomes exactly
divisible by a second, predetermined binary number.
 At the destination, the incoming data unit is divided by the same number. If at
this step there is no remainder, the data unit is assumed to be correct and is
therefore accepted.
 A remainder indicates that the data unit has been damaged in transit and therefore
must be rejected.
Example :

Procedure:
1. Open the editor and type the program for error detection
2. Get the input in the form of bits.
3. Append the redundancy bits.
4. Divide the appended data using a divisor polynomial.
5. The resulting data should be transmitted to the receiver.
6. At the receiver the received data is entered.
7. The same process is repeated at the receiver.
8. If the remainder is zero there is no error otherwise there is some error in the received bits
9. Run the program.

Program:
import java.io.*;
class CRC
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Generator:");
String gen = br.readLine();
System.out.println("Enter Data:");
String data = br.readLine();
String code = data;
while(code.length() < (data.length() + gen.length() - 1))
code = code + "0";
code = data + div(code,gen);
System.out.println("The transmitted Code Word is: " + code);
System.out.println("Please enter the received Code Word: ");
String rec = br.readLine();
if(Integer.parseInt(div(rec,gen)) == 0)
System.out.println("The received code word contains no errors.");
else
System.out.println("The received code word contains errors.");
}

static String div(String num1,String num2)


{
int pointer = num2.length();
String result = num1.substring(0, pointer);
String remainder = "";
for(int i = 0; i < num2.length(); i++)
{
if(result.charAt(i) == num2.charAt(i))
remainder += "0";
else
remainder += "1";
}
while(pointer < num1.length())
{
if(remainder.charAt(0) == '0')
{
remainder = remainder.substring(1, remainder.length()); remainder
= remainder + String.valueOf(num1.charAt(pointer)); pointer++;
}
result = remainder; remainder
= "";
for(int i = 0; i < num2.length(); i++)
{
if(result.charAt(i) == num2.charAt(i)) remainder
+= "0";
else
remainder += "1";
}
}
return remainder.substring(1,remainder.length());
}
}

Result:
Thus the error detection and error correction is implemented successfully
Flow control mechanisms

EX.NO:4(a) Implementation of Sliding Window

Protocol AIM:

To write a java program to perform sliding window protocol

ALGORITHM:

1. Startthe program.
2. Get the frame size from the user
3. Tocreate the frame based on the user request. 4.To send frames to
server from the client side.
5. Ifyour frames reach the server it will send ACK signal to client otherwise it will send NACK signal
to client.
6. Stop the program

Program :

import java.net.*;
import java.io.*; importjava.rmi.*;
public class slidsender
{
public static void main(String a[])throws Exception
{
ServerSocket ser=new ServerSocket(10); Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in); DataInputStream in1=new
DataInputStream(s.getInputStream()); String sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i; String ch;
do
{
p=new PrintStream(s.getOutputStream()); System.out.print("Enter
the no. of frames : "); nf=Integer.parseInt(in.readLine());
p.println(nf); if(nf<=sws-1)
{

System.out.println("Enter "+nf+" Messages to be send\n"); for(i=1;i<=nf;i++)


{
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws-=nf;
System.out.print("Acknowledgment received"); ano=Integer.parseInt(in1.readLine());
System.out.println(" for "+ano+" frames");
sws+=nf;
}
else
{
System.out.println("The no. of frames exceeds window
size"); break;
}
System.out.print("\nDo you wants to send some more frames : ");
ch=in.readLine();
p.println(ch);
}
while(ch.equals("yes"));
s.close();
}
}
RECEIVER PROGRAM
import java.net.*;
import java.io.*;
class slidreceiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuf[]=new
String[8]; String ch;
System.out.println();
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf; System.out.println("\
nAcknowledgment sent\n");
p.println(rptr+1); rws+=nf; }
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
OUTPUT:
//SENDER OUTPUT
Enter the no. of frames : 4
Enter 4 Messages to be
send

hiii
how r
u
i am fine
how is evryone
Acknowledgment received for 4 frames

Do you wants to send some more frames : no


//RECEIVER OUTPUT
The received Frame 0 is : hiii
The received Frame 1 is : how r
u
The received Frame 2 is : i am fine
The received Frame 3 is : how is everyone
EX.NO:4(b) Implementation of Stop and Wait

Protocol AIM

To write a java program to perform sliding window protocol

ALGORITHM:

1. Startthe program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send framesto server from the client side.
5. Ifyour frames reach the server it will send ACK signal to client otherwise it will send
NACK signal to client.
6. Stop the program

PROGRAM

SENDER PROGRAM

import java.io.*;
import java.net.*;
public class Sender
{
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,str,
msg; int
n,i=0,sequence=0;
Sender()
{
}
public void run()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); System.out.println("Waiting for Connection.
");
sender = new
Socket("localhost",2004); sequence=0;

out=new ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
System.out.println("reciver > "+str);
System.out.println("Enter the data to send. ");
packet=br.readLine();
n=packet.length();
do{
try{
if(i<n)
{
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
}
else if(i==n)
{
msg="end";out.writeObject(msg);
break;
}
out.writeObject(msg);
sequence=(sequence==0)?1:0;
out.flush();
System.out.println("data sent>"+msg);
ack=(String)in.readObject();
System.out.println("waiting for ack. \n\n");
if(ack.equals(String.valueOf(sequence)))
{ i+
+;
System.out.println("receiver > "+" packet recieved\n\n");
}
else
{
System.out.println("Time out resending data \n\n");
sequence=(sequence==0)?1:0;
}
}
catch(Exception e)
{
}
}
while(i<n+1);
System.out.println("All data sent. exiting.");
}
catch(Exception e)
{
}
finally
{
try
{
in.close();
out.close();
sender.close();
}
catch(Exception e){}
}
}
public static void main(String args[])
{ Sender s=new Sender();
s.run();
}
}

//RECEIVER PROGRAM

import java.io.*;
import java.net.*;
public class
Reciever
{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Reciever(){}
public void run()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); reciever = new ServerSocket(2004,10);
System.out.println("waiting for connection...");
connection=reciever.accept();
sequence=0;
System.out.println("Connection established :");
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
out.writeObject("connected .");
do
{
try{ packet=(String)in.readObject
();
if(Integer.valueOf(packet.substring(0,1))==sequence)
{
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver >"+packet);
}
else
{
System.out.println("\n\nreceiver >"+packet +" duplicate data");
}
if(i<3)
{
out.writeObject(String.valueOf(sequence));i++;
}
else
{
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
}
}
catch(Exception e){}
}while(!packet.equals("end"));
System.out.println("Data recived="+data);
out.writeObject("connection ended .");
}
catch(Exception e){}
finally{
try{ in.close(
);
out.close();
reciever.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){
Reciever s=new Reciever();
while(true){
s.run();
}
}
}
OUTPUT:

//SENDER OUTPUT
Waiting for
Connection.... reciver >
connected .
Enter the data to send....
myname
data sent>0m
waiting for ack.....
receiver > packet
recieved data sent>1y
waiting for ack.....
receiver > packet
recieved data sent>0n
waiting for ack.....
receiver > packet
recieved data sent>1a
waiting for ack.....
Time out resending data....
data sent>1a
waiting for ack.....
receiver > packet
recieved data sent>0m
waiting for ack.....
receiver > packet
recieved data sent>1e

waiting for ack.....


receiver > packet
recieved All data sent. exiting.

//RECEIVER OUTPUT
waiting for connection...
Connection established :
receiver >0m
receiver >1y
receiver >0n
receiver >1a
receiver >1a duplicate data
receiver >0m
receiver >1e
Data recived=myname
waiting for connection...

Result:
Thus the flow control mechanism is implemented successfully.
Multi-client chatting in TCP and UDP using Socket programming

EXNO:5

AIM
To write a java program for application using TCP Sockets Links

PROCEDURE:
 In the TCP Echo client a socket is created. Using the socket a connection is made to the
server using the connect() function. After a connection is established, we send messages
input from the user and display the data received from the server using send() and read()
functions.
 In the TCP Echo server, we create a socket and bind to a advertized port number. After
binding the process listens for incoming connections. Then an infinite loop is started to
process the client requests for connections. After a connection is requested, it accepts the
connection from the client machine and forks a new process.
 The new process receives data from the lient using recv() function and echoes the same
data using the send() function. Please note hat this server is capable of handling multiple
clients as it forks a new process for every client trying to connect to the server. TCP socket
routines enable reliable IP communication using the transmission control protocol (TCP).
 The implementation of the Transmission Control Protocol (TCP) in the Network
Component. TCP runs on top of the Internet Protocol (IP). TCP is a connection-oriented
and reliable, full duplex protocol supporting a pair of byte streams, one for each direction.
 A TCP connection must be established before exchanging data. TCP retransmits data that
do not reach the final destination due to errors or data corruption. Data is delivered in the
sequence of its transmission

a.Echo client and echo server

ALGORITHM

Client
1. Start
2. Create the TCP socket
3. Establish connection with the server
4. Get the message to be echoed from the user
5. Send the message to the server
6. Receive the message echoed by the server
7. Display the message received from the server
8. Terminate the connection
9. Stop

Server
1. Start
2. Create TCP socket, make it a listening socket
3. Accept the connection request sent by the client for connection establishment
4. Receive the message sent by the client
5. Display the received message
6. Send the received message to the client from which it receives
7. Close the connection when client initiates termination and server becomes a listening
server, waiting for clients.
8. Stop.

PROGRAM:
EchoServer.java
import java.net.*;
import java.io.*;
public class EServer
{
public static void main(String args[])
{
ServerSocket s=null;
String line;
DataInputStream is;
PrintStream ps;
Socket c=null;
try
{
s=new ServerSocket(9000);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();
ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}

EClient.java
import java.net.*;
import java.io.*;
public class
EClient
{ public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
InetAddress ia =
InetAddress.getLocalHost(); c=new
Socket(ia,9000);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
while(true)
{
System.out.println("Client:");
line=is.readLine();
os.println(line);
System.out.println("Server:" + is1.readLine());
}
}
catch(IOException e)
{
System.out.println("Socket Closed!");
}
}}
OUTPUT
Server
C:\Program Files\Java\jdk1.5.0\bin>javac EServer.java C:\
Program Files\Java\jdk1.5.0\bin>java EServer C:\
Program Files\Java\jdk1.5.0\bin>
Client
C:\Program Files\Java\jdk1.5.0\bin>javac EClient.java
C:\Program Files\Java\jdk1.5.0\bin>java EClient
Client: Hai Server
Server:Hai Server
Client: Hello
Server:Hello
Client:end
Server:end
Client:ds
Socket Closed!

B.Chat

ALGORITHM

Client
1. Start
2. Create the UDP datagram socket
3. Get the request message to be sent from the user
4. Send the request message to the server
5. If the request message is “END” go to step 10
6. Wait for the reply message from the server
7. Receive the reply message sent by the server
8. Display the reply message received from the server
9. Repeat the steps from 3 to 8
10. Stop
Server
1. Start
2. Create UDP datagram socket, make it a listening socket
3. Receive the request message sent by the client
4. If the received message is “END” go to step 10
5. Retrieve the client’s IP address from the request message received
6. Display the received message
7. Get the reply message from the user
8. Send the reply message to the client
9. Repeat the steps from 3 to 8.
10. Stop.

PROGRAM
UDPserver.java
import java.io.*;
import java.net.*;
class UDPserver
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int clientport=789,serverport=790;
public static void main(String args[])throws Exception
{
ds=new DatagramSocket(clientport);
System.out.println("press ctrl+c to quit the program");
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
InetAddress ia=InetAddress.geyLocalHost();
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("Client:" + psx);
System.out.println("Server:");
String str=dis.readLine();
if(str.equals("end"))
break;
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,serverport));
}
}
}
UDPclient.java
import java .io.*;
import java.net.*;
class UDPclient
{
public static DatagramSocket ds;
public static int clientport=789,serverport=790;
public static void main(String args[])throws Exception
{
byte buffer[]=new byte[1024];
ds=new DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.println("server waiting");
InetAddress ia=InetAddress.getLocalHost();
while(true)
{
System.out.println("Client:");
String str=dis.readLine();
if(str.equals("end"))
break;
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new
String(p.getData(),0,p.getLength());
System.out.println("Server:" + psx);
}
}
}

OUTPUT:
Server

C:\Program Files\Java\jdk1.5.0\bin>javac UDPserver.java C:\


Program Files\Java\jdk1.5.0\bin>java UDPserver
press ctrl+c to quit the program
Client:Hai Server
Server:Hello Client
Client:How are You
Server:I am Fine

Client
C:\Program Files\Java\jdk1.5.0\bin>javac UDPclient.java
C:\Program Files\Java\jdk1.5.0\bin>java UDPclient
server waiting

Client:Hai Server
Server:Hello Clie
Client:How are You
Server:I am Fine

Result:
Multi-client chatting in TCP and UDP using Socket programming is executed successfully.
Implementation of HTTP, Web Caching, FTP using socket programming

EXNO:6
To write a java program for socket for HTTP for web page upload and download .

procedure:
 HTTP means HyperText Transfer Protocol. HTTP is the underlying protocol used by
the World Wide Web and this protocol defines how messages are formatted and
transmitted, and what actions Web servers and browsers should take in response to
various commands.
 For example, when you enter a URL in your browser, this actually sends an HTTP
command to the Web server directing it to fetch and transmit the requested Web
page.
 The other main standard that controls how the World Wide Web works is HTML,
which covers how Web pages are formatted and displayed. HTTP functions as
a request–response protocol in the client–server computing model.
 A web browser, for example, may be the client and an application running on
a computer hosting a website may be the server.
 The client submits an HTTP request message to the server. The server, which
provides resources such as HTML files and other content, or performs other
functions on behalf of the client, returns a responsemessage to the client.
 The response contains completion status information about the request and may
also contain requested content in its message body.

ALGORITHM:

Client:
1. Start.
2. Create socket and establish the connection with the server.
3. Read the image to be uploaded from the disk
4. Send the image read to the server
5. Terminate the connection
6. Stop.

Server:
1. Start
2. Create socket, bind IP address and port number with the created socket and make server
a listening server.
3. Accept the connection request from the client
4. Receive the image sent by the client.
5. Display the image.
6. Close the connection.
7. Stop.
PROGRAM
Client

import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage; import
java.io.ByteArrayOutputStream; import
java.io.File;
import java.io.IOException; import
javax.imageio.ImageIO;
public class Client
{
public static void main(String args[]) throws Exception
{
Socket soc;
BufferedImage img =
null; soc=new
Socket("localhost",4000);
System.out.println("Client is running.
");
try {
System.out.println("Reading image from disk. ");
img = ImageIO.read(new
File("digital_image_processing.jpg")); ByteArrayOutputStream
baos = new ByteArrayOutputStream(); ImageIO.write(img,
"jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray(); baos.close();
System.out.println("Sending image to server.");
OutputStream out = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();

}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
soc.close();
}
soc.close();
}
}

Server

import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server
{
public static void main(String args[]) throws Exception
{
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
System.out.println("Server Waiting for
image");
socket=server.accept(); System.out.println("Client
connected."); InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new
ByteArrayInputStream(data); BufferedImage
bImage = ImageIO.read(ian); JFrame f = new
JFrame("Server");
ImageIcon icon = new
ImageIcon(bImage); JLabel l = new
JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}
OUTPUT:
When you run the client code, following output screen would appear on client side.

Result:
Thus socket for HTTP for web page upload and download is executed successfully.
Develop a DNS client server to resolve the given host name or IP address

EXNO:7

AIM
To write a java program for DNS application

PROCEDURE:

 The Domain Name System (DNS) is a hierarchical decentralized naming system for
computers, services, or other resources connected to the Internet or a private network. It
associates various information with domain names assigned to each of the participating
entities.
 The domain name space refers a hierarchy in the internet naming structure. This
hierarchy has multiple levels (from 0 to 127), with a root at the top. The
following diagram shows the domain name space hierarchy.
 Name server contains the DNS database. This database comprises of various names and
their corresponding IP addresses. Since it is not possible for a single server to maintain
entire DNS database, therefore, the information is distributed among many DNS
servers.
 Types of Name Servers
 Root Server is the top level server which consists of the entire DNS tree. It does not
contain the information about domains but delegates the authority to the other
server
 Primary Server stores a file about its zone. It has authority to create, maintain, and
update the zone file.
 Secondary Server transfers complete information about a zone from another server which
may be primary or secondary server. The secondary server does not have authority to
create or update a zone file.
 DNS is a TCP/IP protocol used on different platforms. The domain name space is
divided into three different sections: generic domains, country domains, and inverse
domain.
 The main function of DNS is to translate domain names into IP Addresses, which
computers can understand. It also provides a list of mail servers which accept Emails for
each domain name. Each domain name in DNS will nominate a set of name servers to
be authoritative for its DNS records.

ALGORITHM
Server
1. Start
2. Create UDP datagram socket
3. Create a table that maps host name and IP address
4. Receive the host name from the client
5. Retrieve the client’s IP address from the received datagram
6. Get the IP address mapped for the host name from the table.
7. Display the host name and corresponding IP address
8. Send the IP address for the requested host name to the client
9. Stop.
Client
1. Start
2. Create UDP datagram socket.
3. Get the host name from the client
4. Send the host name to the server
5. Wait for the reply from the server
6. Receive the reply datagram and read the IP address for the requested host name
7. Display the IP address.
8. Stop.

PROGRAM
DNS Server
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 IOExceptio
{
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"); 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
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();
}}

OUTPUT
Server
javac udpdnsserver.java
java udpdnsserver
Press Ctrl + C to Quit Request for host yahoo.com
Request for host cricinfo.com
Request for host youtube.com

Client
>javac udpdnsclient.java
>java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
>java udpdnsclient
Enter the hostname : cricinfo.com
IP Address: 80.168.92.140
>java udpdnsclient
Enter the hostname : youtube.com
IP Address: Host Not Found

RESULT:
Thus the java application program using UDP Sockets to implement DNS was developed and
executed successfully
Simulation of unicast routing protocols

EXNO:8

AIM:
To write a ns2 program for implementing unicast routing protocol.

PROCEDURE:

 When a device has multiple paths to reach a destination, it always selects one path
by preferring it over others. This selection process is termed as Routing. Routing
is done by special network devices called routers or it can be done by means of
software processes.
 The software based routers have limited functionality and limited scope.A router
is always configured with some default route. A default route tells the router
where to forward a packet if there is no route found for specific destination.
 In case there are multiple path existing to reach the same destination, router can
make decision based on the following information.Routes can be statically
configured or dynamically learnt. One route can be configured to be preferred over
others.Most of the traffic on the internet and intranets known as unicast data or
unicast traffic is sent with specified destination. Routing unicast data over the
internet is called unicast routing.
 It is the simplest form of routing because the destination is already known. Hence
the router just has to look up the routing table and forward the packet to next hop.
 Multicasting in computer network is a group communication, where a sender(s)
send data to multiple receivers simultaneously. It supports one – to – many and
many – to – many data transmission across LANs or WANs. Through the process
of multicasting, the communication and processing overhead of sending the same
data packet or data frame in minimized.
 Multicast IP Routing protocols are used to distribute data (for example,
audio/video streaming broadcasts) to multiple recipients. Using multicast, a
sourcecan send a single copy of data to a single multicast address, which is then
distributed to an entire group of recipients.
 The key difference between broadcast and multicast is that in the broadcast the
packet is delivered to all the host connected to the network whereas, in
multicast packet is delivered to intended recipients only.
 Multicast Message. Multicasting identifies logical groups of computers. Asingle
message can then be sent to the group. Multicast Message.
Multicasting uses the Internet Group Management Protocol (IGMP) to identify
groups and group members.
ALGORITHM:
1. Start the program.
2. Declare the global variables ns for creating a new simulator.
3. Set the color for packets.
4. Open the network animator file in the name of file2 in the write mode.
5. Open the trace file in the name of file 1 in the write mode.
6. Set the unicast routing protocol to transfer the packets in network.
7. Create the required no of nodes.
8. Create the duplex-link between the nodes including the delay time,bandwidth
and dropping queue mechanism.
9. Give the position for the links between the nodes.
10. Set a tcp reno connection for source node.
11. Set the destination node using tcp sink.
12. Setup a ftp connection over the tcp connection.
13. Down the connection between any nodes at a particular time.
14. Reconnect the downed connection at a particular time.
15. Define the finish procedure.
16. In the definition of the finish procedure declare the global variables ns, file1, and file2.
17. Close the trace file and name file and execute the network animation file.
18. At the particular time call the finish procedure.
19. Stop the program.

PROGRAM:
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace file
set file1 [open out.tr 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 3
}
# Next line should be commented out to have the static routing
$ns rtproto DV
#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]
#Create links between the nodes
$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n2 0.3Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n4 0.3Mb 10ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 0.5Mb 10ms DropTail

#Give node position (for NAM)


$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n1 $n4 orient up-left
$ns duplex-link-op $n3 $n5 orient left-up
$ns duplex-link-op $n4 $n5 orient right-up

#Setup a TCP connection


set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n5 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection


set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

$ns rtmodel-at 1.0 down $n1 $n4


$ns rtmodel-at 4.5 up $n1 $n4
$ns at 0.1 "$ftp start"
$ns at 6.0 "finish"
$ns run
RESULT:
Thus unicast routing protocols was developed andexecuted successfully.
Observing Packets across the network and Performance Analysis of various Routing protocols

EXNO:9

DISTANCE VECTOR ROUTING ALGORITHM

ALGORITHM:
1. Create a simulator object
2. Set routing protocol to Distance Vector routing
3. Trace packets on all links onto NAM trace and text trace file
4. Define finish procedure to close files, flush tracing and run NAM
5. Create eight nodes
6. Specify the link characteristics between nodes
7. Describe their layout topology as a octagon
8. Add UDP agent for node n1
9. Create CBR traffic on top of UDP and set traffic parameters.
10. Add a sink agent to node n4
11. Connect source and the sink
12. Schedule events as follows:
a. Start traffic flow at 0.5
b. Down the link n3-n4 at 1.0
c. Up the link n3-n4 at 2.0
d. Stop traffic at 3.0
e. Call finish procedure at 5.0
13. Start the scheduler
14. Observe the traffic route when link is up and down
15. View the simulated events and trace file analyze it
16. Stop
PROGRAM
#Distance vector routing protocol – distvect.tcl
#Create a simulator object
set ns [new Simulator]
#Use distance vector routing
$ns rtproto DV
#Open the nam trace
file set nf [open out.nam
w]
$ns namtrace-all
$nf # Open tracefile
set nt [open trace.tr w]
$ns trace-all $nt
#Define 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam -a out.nam &
exit 0
}
# Create 8 nodes
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]
set n8 [$ns node]
# Specify link characterestics
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n6 1Mb 10ms DropTail
$ns duplex-link $n6 $n7 1Mb 10ms DropTail
$ns duplex-link $n7 $n8 1Mb 10ms DropTail
$ns duplex-link $n8 $n1 1Mb 10ms DropTail
# specify layout as a octagon
$ns duplex-link-op $n1 $n2 orient left-up
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n4 $n5 orient right
$ns duplex-link-op $n5 $n6 orient right-down
$ns duplex-link-op $n6 $n7 orient down
$ns duplex-link-op $n7 $n8 orient left-down
$ns duplex-link-op $n8 $n1 orient left
#Create a UDP agent and attach it to node n1
set udp0 [new Agent/UDP]
$ns attach-agent $n1 $udp0
#Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node
n4 set null0 [new Agent/Null]
$ns attach-agent $n4 $null0
#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0
#Schedule events for the CBR agent and the network dynamics
$ns at 0.0 "$n1 label Source"
$ns at 0.0 "$n4 label Destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n3 $n4
$ns rtmodel-at 2.0 up $n3 $n4
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run

OUTPUT
$ ns distvect.tcl
RESULT:

Thus the simulation for Distance vector and link state routing protocols was done usingNS2.
B ) LINK STATE ROUTING ALGORITHM

ALGORITHM:

1. Define new simualtor


2. Define different colors for data flows (for NAM)
3. Define a new Trace file and open it
4. Define a new NAM Trace file and open it
5. Define a 'finish' procedure – to flush trace record in the `trace and trace output files.
6. Define the routing protocol as Link State (LS)
7. Create six nodes – n0,n1,..n5
8. Create links between the nodes with 0.3Mb and 10 ms Link with DropTail option
9. Give node position (for NAM) to place six nodes in the layout
10. Setup a TCP connection – attach TCP Source Agent to node n0 and TCP sink agent to
node n5
11. Setup a FTP over TCP connection
12. Define configuration such that link between nodes n1 and n4 to be failed at 1.0 interval,
and up again at 4.5 interval
13. Start the
simulation PROGRAM
#routing2.tcl

set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the Trace file


set file1 [open routing2.tr w]
$ns trace-all $file1

#Open the NAM trace file


set file2 [open routing2.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 routing2.nam &
exit 0
}
# Next line should be commented out to have the static routing
$ns rtproto LS

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

#Create links between the nodes


$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n2 0.3Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n4 0.3Mb 10ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 0.5Mb 10ms DropTail

#Give node position (for NAM)

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


$ns duplex-link-op $n1 $n2 orient right
$ns duplex-link-op $n2 $n3 orient up-down
$ns duplex-link-op $n1 $n4 orient up-left
$ns duplex-link-op $n3 $n5 orient left-up
$ns duplex-link-op $n4 $n5 orient right-up

#Setup a TCP connection


set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n5 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection set


ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

$ns rtmodel-at 1.0 down $n1 $n4


$ns rtmodel-at 3.0 up $n1 $n4
$ns at 0.1 "$ftp start"
$ns at 6.0 "finish"
$ns run

OUTPUT

Before Link failure between Nodes n1 and n4

While Link failure between Nodes n1 and n4


After failed link between Nodes n1 and n4 up
Simulation of Transport layer Protocols and analysis of congestion control
techniques in the network.
Ex.No.10
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 $n4orient left


set udp0 [new Agent/UDP]
$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

You might also like