CN Lab Manual-2-60

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

EX-NO.

1 SIMULATING OF PING COMMAND

AIM:
To writea java program for simulating ping commands

ALGORITHM:

1. Start theprogram.
2. Get the frame size from theuser
3. To create the frame based on the user request.
4.To send frames to server from the clientside.
5. If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal toclient.
6. Stop theprogram

PROGRAM:

//pingclient.java
import java.io.*;
import java.net.*;
importjava.util.Calendar;
class pingclient
{
public static void main(String args[])throws Exception
{
String str;
int c=0;
long t1,t2;
Socket s=new Socket("127.0.0.1",5555);
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
while(c<4)
{
t1=System.currentTimeMillis();
str="Welcome to network programming world";
out.println(str);
System.out.println(dis.readLine());
t2=System.currentTimeMillis();
System.out.println(";TTL="+(t2-t1)+"ms");
c++;
}
s.close();

NETWORKS LAB (JAGADEESH.N/AP) Page 2


//pingserver.javaim
port java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
class pingserver
{
public static void main(String args[])throws Exception
{
ServerSocketss=new ServerSocket(5555);
Socket s=ss.accept();
int c=0;
while(c<4)
{
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
String str=dis.readLine();
out.println("Reply from"+InetAddress.getLocalHost()+";Length"+str.length());
c++;
}
s.close();
}
}

Output:
SERVER

NETWORKS LAB (JAGADEESH.N/AP) Page 3


CLIENT

RESULT:

Thus the program was implementing to simulating ping and traceroute commands

NETWORKS LAB (JAGADEESH.N/AP) Page 4


Ex.No:2 COMMAND AND PROTOCOL ANALYZER

AIM:
A. To learn to use commands like tcpdump, netstat, ifconfig, nslookup and
traceroute
B. Capture ping and trace route PDUs using a network protocol analyzer and
examine.
PROCEDURE:
1. Tcpdump
1. tcpdump -i eth1
2. tcpdump -i eth1 -nn-s0-vport 80
 -i : Select interface that the capture is to take place on, this will often be an ethernet card or
wireless adapter.
 -nn : A single (n) will not resolve hostnames. A double (nn) will not resolve hostnames or
ports. This is handy for not only viewing the IP / port numbers but also when capturing a
large amount of data, as the name resolution will slow down the capture.
 -s0 : Snap length, is the size of the packet to capture.
o -s0 will set the size to unlimited - use this if you want to capture all the traffic.
 -v : Verbose, using (-v) or (-vv) increases the amount of detail shown in the output, often
showing more protocol specific information.
 port 80 : this is a common port filter to capture only traffic on port 80

Capture UDP/TCP traffic


3.tcpdump -i eth0 udp
4.tcpdump -i eth0 proto 6
Capture Hosts based on IP address
5. tcpdump -i eth0 host 10.10.1.1
6. tcpdump -i eth0 dst 10.10.1.20
7. tcpdump -i eth0 -s0 -w test.pcap
8. tcpdump -r 0001.pcap
 The host filter will capture traffic going to (destination) and from (source) the IP address
 Alternatively capture only packets going one way using src or dst.
 Writing a capture file to disk and reading the written file.

Combine Filters
9. tcpdump -nn -A -s1500 -l | grep "User-Agent:"

NETWORKS LAB (JAGADEESH.N/AP) Page 5


10.tcpdump -s 0 -v -n -l | egrep -i "POST /|GET /|Host:"
11.tcpdump -s 0 -A -n -l | egrep -i "POST /|pwd=|passwd=|password=|Host:"
12. cpdump -nn -A -s0 -l | egrep -i 'Set-Cookie|Host:|Cookie:'
13.tcpdump -n icmp
14.tcpdump -D
 By using this option the output is sent immediately to the piped command giving an
immediate response when troubleshooting.
 To list the number of available interfaces on the system.

2. ifconfig

 ifconfig is a system administration utility in Unix-like operating systems for network


interface configuration. It has features for configuring, controlling, and querying TCP/IP
network interface parameters
1. ifconfig // View All Network Setting
2. ifconfig –a // Display Information of All Network Interfaces
3. ifconfig eth0 // View Network Settings of Specific Interface
4. ifconfig eth0 up // to Enable an Network Interface
5. ifconfig eth0 down // to Disable an Network Interface
6. ifconfig eth0 172.16.25.125 // to Assign a IP Address to Network Interface

3. nslookup

 nslookup is a network administrationcommand-line tool available in many computer


operating systems for querying the Domain Name System (DNS) to obtain domain name
or IP address mapping, or other DNS records. The name "nslookup" means "name server
lookup".
1.nslookup example.com
// to find the A record of а domain.
2.nslookup -type=ns example.com
//to check the NS records of a domain.
3.nslookup -type=soa example.com // to query the SOA record of a domain.
4.nslookup -query=mx example.com
//To find the MX records responsible for the email exchange.
5. nslookup -type=any example.com
//To find all of the available DNS records of a domain.

NETWORKS LAB (JAGADEESH.N/AP) Page 6


6.nslookup example.com ns1.nsexample.com
//To check the using of a specific DNS Server.
7.nslookup 10.20.30.40
//To check the Reverse DNS Lookup.
8. nslookup -port=56 example.com
//To change the port number for the connection.
9.nslookup -timeout=20 example.com
//To change the timeout interval for a reply.
10.nslookup -debug example.com
//To enable debug mode.
4. Traceroute
Syntax:tracertwww.example.com
Options:
 -d-Do not resolve addresses to hostnames.
 -h- Maximum number of hops to search for target.
 -j host
 -w timeout
 -R-Trace round-trip path (IPv6-only).
 -S srcaddr-Source address to use (IPv6-only).
 -4-Force using IPv4.
 -6-Force using IPv6.
5. Capture ping and traceroute PDUs

A. Ping Command

To analyze ICMP Echo Request traffic:

1. Observe the traffic captured in the top Wireshark packet list pane. Look for traffic with
ICMP listed as the protocol. To view only ICMP traffic, type icmp (lower case) in the
Filter box and press Enter.
2. Select the first ICMP packet, labeled Echo (ping) request.
3. Observe the packet details in the middle Wireshark packet details pane. Notice that it is
an Ethernet II / Internet Protocol Version 4 / Internet Control Message Protocol frame.
4. Expand Internet Control Message Protocol to view ICMP details.
5. Observe the Type. Notice that the type is 8 (Echo (ping) request).
6. Select Data in the middle Wireshark packet details pane to highlight the data portion of
the frame.
7. Observe the packet contents in the bottom Wireshark packet bytes pane.

NETWORKS LAB (JAGADEESH.N/AP) Page 7


To analyze ICMP Echo Reply traffic:

1. In the top Wireshark packet list pane, select the second ICMP packet, labeled Echo
(ping) reply.
2. Observe the packet details in the middle Wireshark packet details pane. Notice that it is
an Ethernet II / Internet Protocol Version 4 / Internet Control Message Protocol frame.
3. Expand Internet Control Message Protocol to view ICMP details.
4. Observe the Type. Notice that the type is 0 (Echo (ping) reply).
5. Select Data in the middle Wireshark packet details pane to highlight the data portion of
the frame.
6. Observe the packet contents in the bottom Wireshark packet bytes pane. Notice that the
reply echoes the request sequence.
7. Close Wireshark to complete this activity. Quit without saving to discard the captured
traffic.

B.traceroute

1. Start a Wireshark capture.


2. Open a command prompt.
3. Type tracert -d 8.8.8.8 and press Enter to trace the route to one of Google's public DNS
servers. The -d option prevents DNS name resolution, which in this case will improve
performance and reduce the amount of captured traffic.
4. When the trace is complete, close the command prompt.
5. Stop the Wireshark capture.

NETWORKS LAB (JAGADEESH.N/AP) Page 8


Output:
windump

NETWORKS LAB (JAGADEESH.N/AP) Page 9


Ipconfig

NETWORKS LAB (JAGADEESH.N/AP) Page 10


Nslookup

Trace route

RESULT:

Thus the network commands are studied and ping and traceroute PDUs are captured
using a network protocol analyzer. Finally packets are examined.

NETWORKS LAB (JAGADEESH.N/AP) Page 11


EX.NO: 3
DOWNLOAD A WEB PAGE USING TCP SOCKETS.

AIM:
To write a java program using sockets and TCP to download the web page.\

PROCEDURE:
1. Open the Start -> All Programs -> Accessories -> Notepad
2. Save the file name with URLdemo.java
3. Import the necessary statement to the URLdemo.java
4. Create a class called URLdemo with main function
5. In the main function declare the variables and web object of URL with url in constructor
6. Create a con object for URLConnection
7. Display the date, content type, last modification, content length and finally write a code
to display the content of the file.
8. Save and compile the file
Javac URLdemo.java
9. Run the program using
Java URLdemo
10. Finally verify the output.

Code:
URLdemo.java
import java.net.*;
import java.io.*;
importjava.util.Date;
classURLdemo
{
public static void main(String[] arg) throws Exception
{
int c;
URL web = new URL("http://www.mzcet.in/default.aspx");
URLConnection con = web.openConnection();
System.out.println("Date: "+ new Date(con.getDate()));
System.out.println("Content-Type: " + con.getContentType());
System.out.println("Expires: "+ con.getExpiration());
System.out.println("Last-Modified: " + new Date(con.getLastModified()));
intlen = con.getContentLength();

NETWORKS LAB (JAGADEESH.N/AP) Page 12


System.out.println("Content-Length: "+len);
if(len>0)
{
System.out.println("+++++++++CONTENT++++++++");
InputStream input = con.getInputStream();
int i = len;
while(((c = input.read()) != -1) && (--i > 0))
{
System.out.print((char) c);
}
input.close();
}
else
System.out.println("No content available");
}
}

NETWORKS LAB (JAGADEESH.N/AP) Page 13


Output:

NETWORKS LAB (JAGADEESH.N/AP) Page 14


RESULT:

Thus the web page is downloaded using TCP and output is verified.

NETWORKS LAB (JAGADEESH.N/AP) Page 15


EX.NO: 3A ECHO USING TCP SOCKETS

AIM:
To write a program to implement ECHO.

PROCEDURE:
1. Open the Start -> All Programs -> Accessories -> Notepad
2. Save the file name with echoclient.java and echoserver.java
3. Import the necessary statement to the echoclient.java and echoserver.java
4. Create classes called echoclient.java and echoserver.java with main function.
5. Open the Socket in the server and listen for the client request
6. Create a socket and request the connection in client.
7. Server accepts and establishes the connection.
8. Client receive the message and echo the message to server
9. Compile and execute the echoclient.java&echoserver.java

PROGRAM:
echoclient.java
//echo client.java
import java.io.*;
import java.net.*;
importjava.util.*;
public class echoclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStreamusr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStreamdout=null;
try
{
c=new Socket("127.0.0.1",5678);
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{
}

if(c!=null || usr_inp!=null || dout!=null)


{
String unip;
while((unip=din.readLine())!=null)

NETWORKS LAB (JAGADEESH.N/AP) Page 16


{
dout.writeBytes(""+unip);
dout.writeBytes("\n");
System.out.println("\n the echoed message");
System.out.println(usr_inp.readLine());
System.out.println("\n enter your message");
}
System.exit(0);
}
din.close();
usr_inp.close();
c.close();
}
}

echoserver.java
//echoserver.java
import java.io.*;
import java.net.*;
public class echoserver
{
public static void main(String args[])throws Exception
{
ServerSocket m=null;
Socket c=null;
DataInputStreamusr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStreamdout=null;
try
{
m=new ServerSocket(5678);
c=m.accept();
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{}
if(c!=null || usr_inp!=null)
{
String unip;
while(true)
{
System.out.println("\nMessage from Client...");
String m1=(usr_inp.readLine());
System.out.println(m1);
dout.writeBytes(""+m1);

NETWORKS LAB (JAGADEESH.N/AP) Page 17


dout.writeBytes("\n");
}
}
dout.close();
usr_inp.close();
c.close();
}
}

OUTPUT:
SERVER

CLIENT

RESULT:

Thus the echo is implemented using TCP &sockets in java

NETWORKS LAB (JAGADEESH.N/AP) Page 18


EX.NO: 3B CHAT PROGRAM USING TCP

AIM:
To write a program to implement TCP Chat.
PROCEDURE:
1. Open the Start -> All Programs -> Accessories -> Notepad
2. Save the file name with tcpcli.java and tcpser.java
3. Import the necessary statement to the tcpcli.java and tcpser.java
4. Create classes called tcpcli.java and tcpser.java with main function.

SERVER:
1. Establish the connection of socket.
2. Assign the local Protocol address 3535 to the socket.
3. Move the socket from closed to listener state and provide maximum no. of Connections.
4. Create a new socket connection using client address.
5. Read the data from the socket and display
6. Get the message from the user &Write the data into socket.
7. Repeat steps 4 to 6 till exit is typed
8. Close the socket.

CLIENT:
1. Open the socket.
2. Get the host name and port number 3535 from client.
3. Write a request to the buffer that contain the request number as a byte to the output stream.
4. Get the message from the user.
5. Write to the socket.
6. Set the write operation for success.
7. Read the contents from the socket and print
8. Repeat steps 4 to 7 till exit is typed
9. Close the socket

Program:
Server:
import java.io.*;
import java.net.*;
class tcpser
{
static finalint port = 3535;
public static void main(String args[ ])
{
try
{
ServerSocketss=new ServerSocket(port);

NETWORKS LAB (JAGADEESH.N/AP) Page 19


System.out.println("server started"+ss);
Socket s=ss.accept();
System.out.println("Connection accepted"+s);
String str="hai";
while(!str.equals("exit"))
{
BufferedReader in=new BufferedReader(new BufferedReader(new InputStreamReader
(s.getInputStream())));
str=in.readLine();
System.out.print("Client Says:");
System.out.println(str);
if(str.equals("exit"))
return;
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(new BufferedWriter(new
OutputStreamWriter(s.getOutputStream())),true);
System.out.print("Enter the Message:");
out.println("Client:"+br.readLine());
}
System.out.println("Closing");
s.close();
}
catch(Exception e)
{}
}
}
Client:
import java.io.*;
import java.net.*;
class tcpcli
{
static finalint port = 3535;
public static void main(String args[])
{
try
{
InetAddressaddr=InetAddress.getByName("localhost");
Socket s=new Socket(addr,port);
while(true)
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(new BufferedWriter(new
OutputStreamWriter(s.getOutputStream())),true);
System.out.print("Enter the Message:");
out.println(in.readLine());
BufferedReaderbrr=new BufferedReader(new InputStreamReader(s.getInputStream()));

NETWORKS LAB (JAGADEESH.N/AP) Page 20


System.out.print("Server Says:");
System.out.println(brr.readLine());
}
}
catch(Exception e)
{}
}}

OUTPUT:

SERVER

CLIENT

RESULT:

Thus the chat application is implemented using TCP using sockets in java

NETWORKS LAB (JAGADEESH.N/AP) Page 21


EXPNO: 3 C FILE TRANSFER USING TCP

AIM:
To implement the file transfer using TCP in java.

PROCEDURE:
1. Open the Start -> All Programs -> Accessories -> Notepad
2. Save the file name with ft2server.java and ft2client.java
3. Import the necessary statement to the ft2server.java and ft2client.java
4. Create classes ft2server.java and ft2client.java with main function.

CLIENT:
1. Start, import all the necessary packages.
2. Create a client socket and connect to server using port & IP address.
3. Send a file request to server.
4. Then server responses are retrieved using input & output streams.
5. Close the socket.
SERVER:
1. Import all the necessary packages.
2. Create a client and server socket and accept client connection.
3. Transfer files that user requested to transfer using output stream.
4. Close the socket and trace the output.

PROGRAM:

Server:
import java.io.*;
import java.net.*;
importjava.util.*;
public class ft2server
{
public static void main(String args[])throws IOException
{
ServerSocketss=null;
try
{
ss=new ServerSocket(8081);
}
catch(IOException e)
{
System.out.println("couldn't listen");
System.exit(0);
}
Socket cs=null;
try
{

NETWORKS LAB (JAGADEESH.N/AP) Page 22


cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReaderst=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();
System.out.println("The requested file is : "+s);
File f=new File(s);
if(f.exists())
{
BufferedReader d=new BufferedReader(new FileReader(s));
String line;
while((line=d.readLine())!=null)
{
put.write(line);
put.flush();
}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}
}
}
Client:
import java.io.*;
import java.net.*;
importjava.util.*;
public class ft2client
{
public static void main(String srgs[])throws IOException
{
Socket s=null;
BufferedReader get=null;
PrintWriter put=null;
try
{
s=new Socket("127.0.0.1",8081);

NETWORKS LAB (JAGADEESH.N/AP) Page 23


get=new BufferedReader(new InputStreamReader(s.getInputStream()));
put=new PrintWriter(s.getOutputStream(),true);
}
catch(Exception e)
{
System.exit(0);
}
String u,f;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File(f);
FileOutputStreamfs=new FileOutputStream(f1);
while((u=get.readLine())!=null)
{
bytejj[]=u.getBytes();
fs.write(jj);

}
fs.close();
System.out.println("File received");
s.close();
}
}

NETWORKS LAB (JAGADEESH.N/AP) Page 24


OUTPUT:

CLIENT:

SERVER:

RESULT:

Thus file transfer is implemented using TCP and Sockets in java program.

NETWORKS LAB (JAGADEESH.N/AP) Page 25


EX-NO 4 SIMULATION OF DNS

AIM:
To write a java program to simulate DNS.

PROCEDURE:
1. Open the Start -> All Programs -> Accessories -> Notepad
2. Save the file name with Udpdnsserver.java and Udpdnsclient.java
3. Import the necessary statement to the Udpdnsserver.java and Udpdnsclient.java
4. Create classes Udpdnsserver.java and Udpdnsclient.java with main function.

Server:
1. Import all the necessary packages.
2. Create a client and server socket and accept client connection.
3. Create a string array with host and ip with its value.
4. Listen to the request from client
5. If you receive request with hostname then respond with the respective ip address.
6. Close the socket and trace the output.
Client:
1. Start, import all the necessary packages.
2. Create a client socket and connect to server using port & IP address of the server.
3. Get the users input a hostname and parse it to the server.
4. Then server responses are retrieved using output streams.
5. Close the socket.

PROGRAM:
Udpdnsserver.java
// UDP DNS Server
import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static intindexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i <array.length; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};

NETWORKS LAB (JAGADEESH.N/AP) Page 26


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)
{
DatagramSocketserversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacketrecvpack = new DatagramPacket
(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddressipaddress = 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)];
elsecapsent = "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
import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
DatagramSocketclientsocket = new DatagramSocket();
InetAddressipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
intportaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();

NETWORKS LAB (JAGADEESH.N/AP) Page 27


senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length, ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacketrecvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}
}

OUTPUT
CLIENT

SERVER

RESULT:
Thus the function of DNS is simulated using java program.

NETWORKS LAB (JAGADEESH.N/AP) Page 28


EX.NO:5 A Simulating of ARP

AIM:
To write a java program for simulating ARP protocols

PROCEDURE:
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Receive the logical address.
4. Find and reply with the MAC address that matches with the IP address.
5. Close all streams.
6. Close the server socket.
7. Stop.
Client
1. Create a client socket and connect it to the server‟s port number.
2. Retrieve its own IP address using built-in function or get IP address as user input.
3. Send its address to the server.
4. Receive the MAC address from the server and display.
5. Close the input and output streams.
6. Close the client socket.
7. Stop.
Program
Serverarp.java
import java.io.*;
import java.net.*;
importjava.util.*;
classServerarp
{
public static void main(String args[])
{
try
{
ServerSocketobj=new ServerSocket(139);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStreamdout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{

NETWORKS LAB (JAGADEESH.N/AP) Page 29


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

NETWORKS LAB (JAGADEESH.N/AP) Page 30


OUTPUT

RESULT:

Thus the Simulation of the ARP protocol is done using java program.

NETWORKS LAB (JAGADEESH.N/AP) Page 31


EX.NO:5B SIMULATING OF RARP

AIM:
To write a java program for simulating RARP protocols

PROCEDURE:
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Receive the physical address.
4. Find and reply with the IP address that matches with the MAC address.
5. Close all streams.
6. Close the server socket.
7. Stop.
Client
1. Create a client socket and connect it to the server‟s port number.
2. Retrieve its own MAC address using built-in function or get MAC address as user input.
3. Send its address to the server.
4. Receive the MAC address from the server and display.
5. Close the input and output streams.
6. Close the client socket.
7. Stop.
Program
Serverrarp12.java
import java.io.*;
import java.net.*;
importjava.util.*;
class Serverrarp12
{
public static void main(String args[])
{
try
{
DatagramSocket server=new DatagramSocket(1309);
while(true)
{
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
//System.out.println(s);
InetAddressaddr=receiver.getAddress();
int port=receiver.getPort();

NETWORKS LAB (JAGADEESH.N/AP) Page 32


String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(mac[i]))
{
sendbyte=ip[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Clientrarp12.java
import java.io.*;
import java.net.*;
importjava.util.*;
class Clientrarp12
{
public static void main(String args[])
{
try
{
DatagramSocket client=new DatagramSocket();
InetAddressaddr=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());

NETWORKS LAB (JAGADEESH.N/AP) Page 33


System.out.println("The Logical Address is(IP): "+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output

Result:

Thus the Simulation of the RARP protocol is done using java program.

NETWORKS LAB (JAGADEESH.N/AP) Page 34


Ex.No:6 STUDY OF NETWORK SIMULATOR (NS) AND SIMULATION OF
CONGESTION CONTROL ALGORITHMS USING NS
AIM:
To study about network simulator.
PROCEDURE:
History Behind Ns :
The goal of the VINT project, collaborative project between USC/1S, LBL /UC
Berkeley, and Xerox PARC, is to extend the ns simulator so that network researchers can study
the complex interactions between network protocols (e.g. unicast routing, multicast routing,
TCP, reliable multicast, integrated services, etc..) in complex topologies and with a rich set of
traffic generators. The primary components of the simulator are scheduler, connection oriented
and connectionless protocols, trace support routing, topology generation, multicast support and
queue management. Further various issues in adding new routing or transport protocols,
scheduling algorithms, link layers, applications, or visualization tools to ns can be implemented.
The Event Driven Network Simulator – Ns :
NS is an event driven network simulator developed at UC Berkeley that simulates variety
of IP networks. It implements network protocols such as TCP and UDP, traffic source behavior
such as FIP, Telnet, Web, CBR and VBR, router queue management mechanism such as
DropTail, RED and CBQ, routing algorithms such as Dijkstra, and many more. NS also
implements multicasting and some of the MAC layer protocols for LAN simulations. The NS
project is now a part of the VINT Project develops tools for simulation results display, analysis
and converters that convert network topologies generated by well-known generators to NS
formats. Currently NS (version 2) written in C++ and OTcl (Tel script language with Object-
oriented extension developed at MIT) is available.
Diagram:

The Object - Oriented Tcl Script Interpreter :

NETWORKS LAB (JAGADEESH.N/AP) Page 35


In a simplified user’s view, NS is Object-oriented Tcl (OTcl) script interpreter that has an
simulation event scheduler and network Component object libraries, and network component
object libraries, and network setup (plumbing) module libraries (actually, plumbing modules are
implemented as member functions of the base s1muator object). To setup and run a simulation
network, a user should write an OTcl script that initiates an event scheduler, sets up the network
topology using the network objects and the plumbing functionsin the library and tells traffic
sources when to start and stop transmitting packets through the event scheduler.
C++ And Otcl : The Duality
The following figure shows an object hierarchy example in c++ and Otcl.One thing to
note in the fIgure is that for C++ objects that have an OTcl linkage forming a hierarchy, there
is a matching OTcl object hierarchy very similar to that of C++.

The Necessity Of Two Languages C++ And Tcl:


Network Simulator NS makes use of two languages for simulation this is because
simulator has two different kinds of things it needs to do.
 On one hand, detailed simulations of protocols require 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.

 Moreover, 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.

NETWORKS LAB (JAGADEESH.N/AP) Page 36


 To meet both of these needs we make use of two languages, C++ and OTcl. C++
is fast to run but slower to change, making it suitable for detailed protocol
implementation. OTcl runs much slower but can be changed very quickly (and
interactively), making it ideal for simulation configuration.

Making Use OfTcl:


• For configuration, setup, and “one-time”stuff
• Manipulating existing C++ objects for performing the things required
Making Use Of C++:
• processing each packet of a flow
• changing the behavior of an existing C++ class in ways that weren’t anticipated
Architectural View Of Ns :

The above figure shows the general architecture of NS and a general user (not an NS
developer) can be thought of standing at the left bottom corner, designing and running-
simulations in Tcl using the simulator objects in the OTcl library. The event schedulers and most
of the network components are implemented in C++ and available to OTcl through an OTcl
linkage that is implemented using Tcl. The whole thing together makes NS, which is an object
oriented extended Tcl interpreter with network simulator libraries.
Obtaining Simulation Results:
When a simulation is finished, NS produces one or more text-based output files that
contain detailed simulation data, if specified to do so in the input Tel (or more specifically, OTcl)
script. The data can be used for simulation analysis or as an input to a graphical simulation
display tool called Network Animator (NAM) that is developed as a part of VINT project. AM
has a nice graphical user interface similar to that of a CD player (play, fast forward, rewind,
pause and so on), and also has a display speed controller. Furthermore, it can graphically present
information such as throughput and number of packet drops at each link, although the graphical

NETWORKS LAB (JAGADEESH.N/AP) Page 37


information cannot be used for accurate simulation analysis.
Simple Simulation Example :

Network Construction:
a) This network. Consists of 4 nodes (n0. n1, n2, n3) as shown in above figure.

b) The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms
of delay.

c) The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay.

d) Each node uses a Drop Tail queue, of which the maximum size is 10.

e) A “tcp” agent is attached to n0, and a connection is established to a tcp “sink” age
attached to n3.

f) As default, the maximum size of a packet that a “tcp” agent can generate is 1Kbyte.

g) A tcp “sink” agent generates and sends ACK packets to he sender (tcp agent) and frees
the received packets.

h) An “udp” agent that is attached to n1 is connected to a “null” agent attached to n3.

i) A “null” agent just frees the packets received.


A “ftp” and a “cbr” traffic generator are attached to “tcp” and “udp” agents respectively,

j) The “cbr” is configured to generate 1 KB packets at the rate of 1 Mbps.

k) The “cbr” is set to start at 0.1 sec and stop at 4.5 sec.

l) The “ftp” is set to start at 1.0 sec and stop at 4.0 Sec.

NETWORKS LAB (JAGADEESH.N/AP) Page 38


Downloading NS:
We can build ns either from the various packages like Tcl/Tk, OTcl or we can download
an ‘all-in-one’ package. But it is very much recommended that we go for the all-in-one package,
especially if we are not entirely sure which packages are installed in the system, and where they
are installed. The disadvantage of the all-in-one distribution is the size, since it some components
that are not required anymore after compiling ns and nam. It’s still good for first tests, and we
can always switch to the single-package distribution later. The thing to be noted is that all-in-one
package only woks on UNIX systems.
Installing NS:
After the installation is complete, make sure that the required path points to the ‘ns-
allinone/bin’ directory (when the ns-allinone package is installed) where links to the ns and
namexecutables in the ‘ns-2’ and ‘nam- 1’ directories can be found or let your path point directly
to the directories with the ns and namexecutables.On some systems we will have to make sure
that ns is able to find the library ‘libotcl.so’. If in the installed package is ns-ailinone package,
then it should be in ‘ns-allinone/OTcl/’.
Starting Nam:
To view the animation of the script that we have written for specific network operations,
we can start with the command ‘nam<nam-file>’ where ‘<nam-file>’ is the name of a nam trace
file that was generated by ns, or it can be directly executed out of the Tel simulation script for the
simulation which is required to visualize.
Two Nodes One Link:
To transmit data from one node to another first two nodes should be constructed as
shown below and a link to be established for transmitting data between the links. The established
link could be either SIMPLEX or DUPLEX according to the network requirements.

Sending Data:
Once nodes constructed and the link established we can have process of transmitting the
following diagram shows the flow of data from node 0 to node 1.

NETWORKS LAB (JAGADEESH.N/AP) Page 39


Monitoring A Queue:
In most situations, to monitor the status of data being transferred from one node to the
other a queue called as monitoring queue is required and how the packets are dropped can be
visualized, in addition to that in improving the performance of the monitoring queue visualized
we can go for a special queue called as - SFQ (stochastic fair queuing).

Creating A Topology:
Once the basic components like node construction, link establishment, setting the type of
source, queue monitors we can go for the construction of required topology, mostly all the
networking simulations are concentrated on the visualization of the effect produced by a
topology as a whole. The following diagram shows the initial basic topology.

NETWORKS LAB (JAGADEESH.N/AP) Page 40


Viewing With AnXgrapb:
When we run the simulation, an xgraph window when required should open as in the
following diagram after some time. Note that the output files created by the ‘record’ procedure
can also be used with gnuplot.

Multicast Routing:

NETWORKS LAB (JAGADEESH.N/AP) Page 41


CONFIGURATION GROUP A GROUP B
NODES {A,B,D} {B,D,C}

Simple Multicast Code:


set ns [new Simulator -multicast on] //Create a Simulator object
set f [open out.tr w] //Open a file for writing trace data
$ns trace-all $f //Record all the tracings
$ns namtrace-all [open out.nam W] //Open Animator file for writing data
$ns color 1 red //Defining Colors for network construction
$ns color 30 purple
$ns color 31 bisque
set n0 [$ns node] //Setting node 0
set n1 [$ns node] // Setting node 1
set n2 [$ns node] //Setting node 2
set n3 [$ns node] //Setting node 3

# Use automatic layout and Establish links


$ns duplex-link $n0 Sn1 1.5Mb 10ms Drop Tail // Establish link for node 0 and node 1

$ns duplex-link Sn1 $n2 1.5Mb 10ms Drop Tail // Establish link for node 1 and node 2

$ns duplex-link Sn1 $n3 1.5Mb 10ms Drop Tail //Establish link for node 1 and node 3

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


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

NETWORKS LAB (JAGADEESH.N/AP) Page 42


$ns duplex-link-op $n0 Sn1 queuePos 0.5
setmproto DM
setmrthandle [$ns mrtproto $mproto {}]
set group0 [Node allocaddr]
set group1 [Node allocaddr]
set udp0 [new Agent/UDP] //Setting Agent as UDP for node 0
$ns attach-agent $n1 $udp0 //Attaching Agent
$udp0 set dst_addr_$group0
$udp0 set dst_port_0
set cbr0 [new Application/Traffic/CBR //Setting Traffic source as CBR
$cbr0 attach-agent $udp0 //Attaching Agent
set udp1 [new Agent/UDP] //Setting Agent as UDP for node 1
$udp1 set dst_addr_$group1
$udp1 set dst_port_0
$udp1 set class_1
$ns attach-agent $n3 $udp1
set cbr1 [new Application/Traffic/CBR] //Setting Traffic source as CBR
$cbr1 attach-agent $udp1
setrcvr[new Agent/LossMonitor] //Receiver Agent
$ns attach-agent $n2 $rcvr
$ns at 1.2 “$n2 join-group $rcvr $group1”
$ns at 1.25 “$n2 leave-group $rcvr $group1”
$ns at 1.3 “$n2 join-group $rcvr $group1”
$ns at 1.35 “$n2 join-group $rcvr $group0”
$ns at 1.0 “$cbr0 start” //Starting point for the Traffic Source
$ns at 1.1 “$cbr1 start”
#set tcp [new Agent/TCP]
#set sink [new Agent/TCPSink] //Setting Sink Agent
#$ns attach-agent $n0 $tcp
#$ns attach-agent $n3 $sink
#$ns connect $tcp $sink
#set ftp [new Application/FTP]
#$ftp attach-agent $tcp
#$ns at 1.2 “$ftp start”
#puts [$cbr0 set packetSize_]
#puts [$cbr0 set interval_]

NETWORKS LAB (JAGADEESH.N/AP) Page 43


$ns at 2.0 “finish” //Setting time for ns to finish at 2.0
proc finish {} //procedure
{
global ns
$ns flush-trace
puts “running nam…” //Display string “running nam…”
execnamout.nam& //Execution of Network Animator
exit 0 //Terminate Statement
}
$ns run // Running NS

At The Prompt:
After editing the code for multicast routing save the file with any file name but with a .tcl
extension and at the UNIX prompt, perform the following.
ns<filename>.tclif (example) ns mcasttd
An output animator file would then be created, the name of the animator file would be
out.nam. Then run the generated output animator file using namavailable in the shell.
Now, the network animation for muhicast programming can be viewed graphically.

RESULT:
Thus the study about network simulator is done.

NETWORKS LAB (JAGADEESH.N/AP) Page 44


EX.NO: 7 STUDY OF TCP/UDP PERFORMANCE USING SIMULATION TOOL

AIM:
To study about the TCP/UDP performance using Simulation tool
PROCEDURE:
1. Create a network simulator object.
2. Define different colors for data flow.
3. Write a finish Procedure to close nam.
4. Create four nodes for the simulation purpose.
5. Then Create link between nodes.
6. Setup nodes position.
7. Setup the UDP connection with the node.
8. Setup the CBR for UDP.
9. Setup the CBR for TCP.
10. Measure the performance.

PROGRAM:

#Create a simulator object


set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the NAM trace file


setnf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
execnamout.nam&
exit 0
}

#Create four nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

#Create links between the nodes


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

NETWORKS LAB (JAGADEESH.N/AP) Page 45


$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

#Set Queue Size of link (n2-n3) to 10


$ns queue-limit $n2 $n3 10

#Give node position (for NAM)


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

#Monitor the queue for link (n2-n3). (for NAM)


$ns duplex-link-op $n2 $n3 queuePos 0.5

#Setup a TCP connection


settcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection


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

#Setup a UDP connection


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

#Setup a CBR over UDP connection


setcbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false

#Schedule events for the CBR and FTP agents


$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"

NETWORKS LAB (JAGADEESH.N/AP) Page 46


#Detachtcp and sink agents (not really necessary)
$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Print CBR packet size and interval


puts "CBR packet size = [$cbr set packet_size_]"
puts "CBR interval = [$cbr set interval_]"

#Run the simulation


$ns run

OUTPUT:

RESULT:
Thus the performance study of TCP/UDP is done successfully using NS2 simulation tool.

NETWORKS LAB (JAGADEESH.N/AP) Page 47


EX:8A SIMULATION OF LINK STATE ROUTING

AIM:
To simulate and study of link state routing.

PROCEDURE:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on
trace file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose Link state routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.

PROGRAM:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
setnf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
execnamthro.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]

NETWORKS LAB (JAGADEESH.N/AP) Page 48


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

NETWORKS LAB (JAGADEESH.N/AP) Page 49


OUTPUT:

RESULT:

Thus the link state routing is studied and simulated.

NETWORKS LAB (JAGADEESH.N/AP) Page 50


EX: 8B SIMULATION OF DISTANCE VECTOR ROUTING ALGORITHM

AIM:
To simulate and study the distance vector routing algorithm using simulation.

ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on
trace file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose distance vector routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.

PROGRAM:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
setnf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
execnamthro.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

NETWORKS LAB (JAGADEESH.N/AP) Page 51


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

NETWORKS LAB (JAGADEESH.N/AP) Page 52


OUTPUT:

RESULT:
Thus the distance vector routing algorithm was simulated and studied.

NETWORKS LAB (JAGADEESH.N/AP) Page 53


EX.NO:9 CASE STUDIES ABOUT THE DIFFERENT ROUTING ALGORITHMS

AIM:
To study the link state routing
PROCEDURE:
i.Link State routing:
Routing is the process of selecting best paths in a network. In the past, the term routing
was also used to mean forwarding network traffic among networks. However this latter function
is much better described as simply forwarding. Routing is performed for many kinds of
networks, including the telephone network (circuit switching), electronic data networks (such as
the Internet), and transportation networks. This article is concerned primarily with routing in
electronic data networks using packet switching technology.
In packet switching networks, routing directs packet forwarding (the transit of logically
addressed network packets from their source toward their ultimate destination) through
intermediate nodes. Intermediate nodes are typically network hardware devices such as routers,
bridges, gateways, firewalls, or switches. General-purpose computers can also forward packets
and perform routing, though they are not specialized hardware and may suffer from limited
performance. The routing process usually directs forwarding on the basis of routing tables which
maintain a record of the routes to various network destinations. Thus, constructing routing tables,
which are held in the router's memory, is very important for efficient routing. Most routing
algorithms use only one network path at a time. Multipath routing techniques enable the use of
multiple alternative paths.
In case of overlapping/equal routes, the following elements are considered in order to decide
which routes get installed into the routing table (sorted by priority):
1. Prefix-Length: where longer subnet masks are preferred (independent of whether it is within a
routing protocol or over different routing protocol)
2. Metric: where a lower metric/cost is preferred (only valid within one and the same routing
protocol)
3. Administrative distance: where a lower distance is preferred (only valid between different
routing protocols)
Routing, in a more narrow sense of the term, is often contrasted with bridging in its
assumption that network addresses are structured and that similar addresses imply proximity
within the network. Structured addresses allow a single routing table entry to represent the route
to a group of devices. In large networks, structured addressing (routing, in the narrow sense)
outperforms unstructured addressing (bridging). Routing has become the dominant form of
addressing on the Internet. Bridging is still widely used within localized environments.

NETWORKS LAB (JAGADEESH.N/AP) Page 54


ii. Flooding
Flooding s a simple routing algorithm in which every incoming packet is sent through
every outgoing link except the one it arrived on.Flooding is used in bridging and in systems such
as Usenet and peer-to-peer file sharing and as part of some routing protocols, including OSPF,
DVMRP, and those used in ad-hoc wireless networks.There are generally two types of flooding
available, Uncontrolled Flooding and Controlled Flooding.Uncontrolled Flooding is the fatal law
of flooding. All nodes have neighbours and route packets indefinitely. More than two
neighbourscreates a broadcast storm.
Controlled Flooding has its own two algorithms to make it reliable, SNCF (Sequence
Number Controlled Flooding) and RPF (Reverse Path Flooding). In SNCF, the node attaches its
own address and sequence number to the packet, since every node has a memory of addresses
and sequence numbers. If it receives a packet in memory, it drops it immediately while in RPF,
the node will only send the packet forward. If it is received from the next node, it sends it back to
the sender.
ALGORITHM:
There are several variants of flooding algorithm. Most work roughly as follows:
1. Each node acts as both a transmitter and a receiver.
2. Each node tries to forward every message to every one of its neighbours except the source
node.
This results in every message eventually being delivered to all reachable parts of the
network. Algorithms may need to be more complex than this, since, in some case, precautions
have to be taken to avoid wasted duplicate deliveries and infinite loops, and to allow messages to
eventually expire from the system. A variant of flooding called selective flooding partially
addresses these issues by only sending packets to routers in the same direction. In selective
flooding the routers don't send every incoming packet on every line but only on those lines
which are going approximately in the right direction.
Advantages
 If a packet can be delivered, it will (probably multiple times).
 Since flooding naturally utilizes every path through the network, it will also use the
shortest path.
 This algorithm is very simple to implement.

Disadvantages:
 Flooding can be costly in terms of wasted bandwidth. While a message may only have
one destination it has to be sent to every host. In the case of a ping flood or a denial of
service attack, it can be harmful to the reliability of a computer network.

NETWORKS LAB (JAGADEESH.N/AP) Page 55


 Messages can become duplicated in the network further increasing the load on the
networks bandwidth as well as requiring an increase in processing complexity to
disregard duplicate messages.
 Duplicate packets may circulate forever, unless certain precautions are taken:
 Use a hop count or a time to live count and include it with each packet. This value should
take into account the number of nodes that a packet may have to pass through on the way
to its destination.
 Have each node keep track of every packet seen and only forward each packet once
 Enforce a network topology without loops

iii . Distance vector:


In computer communication theory relating to packet-switched networks, a distance-
vector routing protocol is one of the two major classes of routing protocols, the other major
class being the link-state protocol. Distance-vector routing protocols use the Bellman–Ford
algorithm, Ford–Fulkerson algorithm, or DUAL FSM (in the case of Cisco Systems's protocols)
to calculate paths. A distance-vector routing protocol requires that a router informs its neighbors
of topology changes periodically. Compared to link-state protocols, which require a router to
inform all the nodes in a network of topology changes, distance-vector routing protocols have
less computational complexity and message overhead.The term distance vector refers to the fact
that the protocol manipulates vectors (arrays) of distances to other nodes in the network. The
vector distance algorithm was the original ARPANET routing algorithm and was also used in the
internet under the name of RIP (Routing Information Protocol). Examples of distance-vector
routing protocols include RIPv1 and RIPv2 and IGRP.
Method:
Routers using distance-vector protocol do not have knowledge of the entire path to a
destination. Instead they use two methods:
1. Direction in which router or exit interface a packet should be forwarded.
2. Distance from its destination
Distance-vector protocols are based on calculating the direction and distance to any link
in a network. "Direction" usually means the next hop address and the exit interface. "Distance" is
a measure of the cost to reach a certain node. The least cost route between any two nodes is the
route with minimum distance. Each node maintains a vector (table) of minimum distance to
every node. The cost of reaching a destination is calculated using arious route metrics. RIP uses
the hop count of the destination whereas IGRP takes into account other information such as node
delay and available bandwidth.
Updates are performed periodically in a distance-vector protocol where all or part of a

NETWORKS LAB (JAGADEESH.N/AP) Page 56


router's routing table is sent to all its neighbors that are configured to use the same distance-
vector routing protocol. RIP supports cross-platform distance vector routing whereas IGRP is a
Cisco Systems proprietary distance vector routing protocol. Once a router has this information it
is able to amend its own routing table to reflect the changes and then inform its neighbors of the
changes. This process has been described as routing by rumor‘ because routers are relying on the
information they receive from other routers and cannot determine if the information is actually
valid and true. There are a number of features which can be used to help with instability and
inaccurate routing information.EGP and BGP are not pure distance-vector routing protocols
because a distance-vector protocol calculates routes based only on link costs whereas in BGP, for
example, the local route preference value takes priority over the link cost.
Count-to-infinity problem:
The Bellman–Ford algorithm does not prevent routing loops from happening and suffers
from the count-to-infinity problem. The core of the count-to-infinity problem is that if A tells B
that it has a path somewhere, there is no way for B to know if the path has B as a part of it. To
see the problem clearly, imagine a subnet connected like A–B–C–D–E–F, and let the metric
between the routers be "number of jumps". Now suppose that A is taken offline. In the vector-
update-process B notices that the route to A, which was distance 1, is down – B does not receive
the vector update from A. The problem is, B also gets an update from C, and C is still not aware
of the fact that A is down – so it tells B that A is only two jumps from C (C to B to A), which is
false. This slowly propagates through the network until it reaches infinity (in which case the
algorithm corrects itself, due to the relaxation property of Bellman–Ford).

RESULT:
Thus the case study is done with different protocols

NETWORKS LAB (JAGADEESH.N/AP) Page 57


EX: 10 SIMULATION OF CRC

AIM:
To write a java program to simulate the CRC technique

PROCEDURE:
1. Open the notepad
2. Import necessary header files.
3. Create a class called CRC with the main function
4. Declare needed variable
5. Implement the CRC code
6. Display the code bit added

PROGRAM:
CRC.java
importjava.util.Scanner;
class CRC
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
intm,g[],n,d[],z[],r[],msb,i,j,k;
System.out.print("Enter no. of data bits : ");
n=sc.nextInt();
System.out.print("Enter no. of generator bits : ");
m=sc.nextInt();
d=new int[n+m];
g=new int[m];
System.out.print("Enter data bits : ");
for(i=0;i<n;i++)
d[i]=sc.nextInt();
System.out.print("Enter generator bits : ");
for(j=0;j<m;j++)
g[j]=sc.nextInt();
for(i=0;i<m-1;i++)
d[n+i]=0;
r=new int[m+n];
for(i=0;i<m;i++)
r[i]=d[i];
z=new int[m];
for(i=0;i<m;i++)
z[i]=0;
for(i=0;i<n;i++)
{
k=0;
msb=r[i];

NETWORKS LAB (JAGADEESH.N/AP) Page 58


for(j=i;j<m+i;j++)
{
if(msb==0)
r[j]=xor(r[j],z[k]);
else
r[j]=xor(r[j],g[k]);
k++;
}
r[m+i]=d[m+i];
}
System.out.print("The code bits added are : ");
for(i=n;i<n+m-1;i++)
{
d[i]=r[i];
System.out.print(d[i]);
}
System.out.print("\nThe code data is : ");
for(i=0;i<n+m-1;i++)
{
System.out.print(d[i]);
}
}
public static intxor(intx,int y)
{
if(x==y)
return(0);
else
return(1);
}
}

NETWORKS LAB (JAGADEESH.N/AP) Page 59


OUTPUT:

RESULT:
Thus the CRC is simulated using java program.

NETWORKS LAB (JAGADEESH.N/AP) Page 60

You might also like