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

CN Lab Manual

Uploaded by

nithish.nk04
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 views72 pages

CN Lab Manual

Uploaded by

nithish.nk04
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/ 72

INDEX

PAGE
E.NO EXPERIMENT NAME
NO
Learn to use commands like tcpdump, netstat, ifconfig, nslookup and trace
1. route. Capture ping and trace route PDUs using a network protocol analyzer
and examine
Write a HTTP web client program to download a web page using
2.
TCP sockets
Applications using TCP sockets like:
a) Echo client and echo server
3.
b) Chat

4. Simulation of DNS using UDP sockets.

5. Use a tool like Wireshark to capture packets and examine the packets.

6. Write a code simulating ARP/RARP protocols.


Study of Network simulator (NS) and Simulation of Congestion
7.
Control Algorithms using NS

8. Study of TCP/UDP performance using Simulation tool.

9. Simulation of Distance Vector/Link State Routing algorithm.

10. Simulation of error correction code(like CRC).

Performance evaluation of Routing protocols using Simulation tool.


11
12 Applications using TCP sockets like: File Transfer
LIST OFEXPERIMENTS
1. Learntousecommandsliketcpdump,netstat,ifconfig,nslookupandtraceroute.Capture
pingandtraceroutePDUsusinganetworkprotocolanalyzerandexamine.

2. Writea HTTPwebclientprogramtodownloada webpageusingTCPsockets.

3. ApplicationsusingTCPsocketslike:

 Echoclientandechoserver
 Chat
 FileTransfer
4. SimulationofDNSusingUDPsockets.

5. WriteacodesimulatingARP/RARPprotocols.

6. Study of Network simulator (NS) and Simulation ofCongestion


ControlAlgorithmsusingNS.

7. StudyofTCP/UDPperformanceusingSimulationtool.

8. SimulationofDistanceVector/LinkStateRoutingalgorithm.

9. PerformanceevaluationofRoutingprotocolsusingSimulationtool.

10. Simulationoferrorcorrection code (likeCRC).

TOTAL: 45 PERIODS
LIST OF EQUIPMENT FOR A BATCH OF 60 STUDENTS

HARDWARE
Stand alone desktops 60Nos
SOFTWARE:
 C/C++/Java/Python/Equivalent Compiler 60Nos.

 Network simulator likeNS2/Glomosim /OPNET/Packet Tracer/Equivalent

JAVA

Javaisahigh-levelprogramminglanguageoriginallydevelopedbySunMicrosystems.
Java runs on a variety of platforms, such as Windows, Mac OS, and
thevariousversionsofUNIX.Javaprogrammingwere"Simple,Robust,Portable,Platform-
independent,Secured,HighPerformance,Multithreaded,ArchitectureNeutral,Object-
Oriented,Interpreted,andDynamic".

NS2

NS2 stands for Network Simulator Version 2. It is an open-source event-driven


simulator designed specifically for research in computer communication networks. It
provides substantial support to simulate bunch of protocols like TCP, FTP, UDP, https
and DSR .It simulates wired and wireless network. It is primarily UNIX based. Uses
TCL as its scripting language.
EX.NO:1 Commands and Trace route PDUs using a network protocol Analyzer

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

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 IPaddress 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.
Traceroute:
Trace route is a network diagnostic tool used to track the pathway taken by a packet on an
IPnetwork from source to destination. Trace route also records the time taken for each hop the packet
makes during its route to the destination

Commands:
Tcpdump:
Displaytrafficbetween2hosts:
To display all traffic between wohosts(representedbyvariableshost1
andhost2) :#tcpdumphosthost1andhost2
Display traffic from a source or destination host only:
To display traffic from only a source (src) or destination (dst)
host:#tcpdump src host
#tcp dump dst host
Display traffic for a specific protocol
Providetheprotocolasanargumenttodisplayonlytrafficforaspecificprotocol,for example tcp, udp, icmp,
arp
#tcpdump protocol
For example to display traffic only for the TCP traffic:
#tcpdumptcp
Filtering based on source or destination port
To filte rbased on a source or destination port:
# tcpdump src port
ftp#tcpdumpdstport
http

2. Netstat
Netstat is a common command line TCP/IP networking available in most versions of Windows,
Linux, UNIX and other operating systems.
NetstatprovidesinformationandstatisticsaboutprotocolsinuseandcurrentTCP/IPnetworkconnections.
The Windows help screen (analogous to a Linux or UNIX for netstat reads as
follows:displaysprotocolstatisticsandcurrentTCP/IPnetworkconnections.

#netstat

3. ipconfig

In Windows, ipconfig is a console application designed to run from the Windows


commandprompt.ThisutilityallowsyoutogettheIPaddressinformationofa Windows computer.
Usingipconfig
From the command prompt, type ipconfig to run the utility with default options. The output of
thedefault command contains the IP address, network mask, and gateway for all physical and virtual
network adapters.
#ipconfig
4. nslookup
The nslookup (which stands for name server lookup) command is a network utility program
usedto 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:

Trace route 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.
Trace route is a network diagnostic tool used to track the pathway taken by a packet on an IP network
from source to destination. Trace route also records the time taken for each hop the packet makes
during its route to the destination. Trace route 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. Trace route
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 packet whose TTL
value 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
routerforwardsthepackets,butthesecondrouterdropsthemandreplieswithICMPTimeExceeded.
Proceeding in this way, trace route 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 host name

www.google.com.#tr

acertgoogle.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
andsoftwareproblems.Determiningthestatusofthenetworkandvariousforeignhosts.Thepingcommand 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 ControlMessage
Protocol (ICMP) Echo Requestmessages tothe destination computerand waitingforaresponse

# ping172.16.6.2
RESULT:
Thus the various networks commands like tcpdump, netstat, ifconfig, nslookup and traceroute
ping are executed successfully.
Ex.No:2 write a HTTP web client program to download a webpage using TCP sockets

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

PRELAB DISCUSSION:
 HTTP means Hyper Text Transfer Protocol. HTTP is the underlying protocol used by
the World Wide Web and this protocol defines show 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 Webpage.
 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 web site 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 response message 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 IPaddress 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

importjavax.swing.*;
importjava.net.*;
importjava.awt.image.*;
importjavax.imageio.*;
importjava.io.*;
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
importjavax.imageio.ImageIO;
PublicclassClient
{
publicstaticvoidmain(Stringargs[])throwsException
{
Socketsoc;BufferedImagei
mg=null;soc=new
Socket("localhost",4000);System.out.pri
ntln("Clientisrunning.

"); try{
System.out.println("Readingimagefromdisk.");
img=ImageIO.read(newFile("digital_image_processing.jpg"));B
yteArrayOutputStream baos = new
ByteArrayOutputStream();ImageIO.write(img,"jpg",baos);
baos.flush();
byte[]bytes=baos.toByteArray();baos.close();System.o
ut.println("Sendingimagetoserver.");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(Exceptione)
{
System.out.println("Exception:"+e.getMessage());
16
soc.close();
}
soc.close();
}
}

Server

importjava.net.*;
importjava.io.*;
importjava.awt.image.*;
importjavax.imageio.*;
importjavax.swing.*;
classServer
{
publicstaticvoidmain(Stringargs[])throwsException
{
ServerSocket
server=null;Socketsocket;
server=new
ServerSocket(4000);System.out.println("Server
Waitingforimage");
socket=server.accept(); System.out.println("Client
connected.");InputStreamin= socket.getInputStream();
DataInputStreamdis=newDataInputStream(in);
intlen=dis.readInt();
System.out.println("ImageSize:"+len/1024+"KB");byte[]data=newbyte[len];
dis.readFully(data);
dis.close();
in.close();
InputStreamian=newByteArrayInputStream(data);
BufferedImagebImage=ImageIO.read(ian);
JFramef=newJFrame("Server");
ImageIconicon=newImageIcon(bImage);
JLabell=newJLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}
OUTPUT:

When you’re in the client code, following output screen would appear on clientside.

RESULT:
Thus the socket program for HTTP for webpage upload and download was developed and
executed successfully.
Ex.No:3 Applications using TCP sockets like: Echo client and Echo server Chat

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

PRELAB DISCUSSION:
 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 client using recv( )function and echoes the same
data using the send() function. Please note that 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
routine senable 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
3. socket, make it a listening socket
4. Accept the connection request sent by the client for connection establishment
5. Receive the message sent by the client
6. Display the received message
7. Send the received message to the client from which it receives
8. Closetheconnectionwhenclientinitiatesterminationandserverbecomesalisteningserver,waitin
gforclients.
9. Stop.

PROGRAM:
EchoServer.java
importjava.net.*;
importjava.io.*;
publicclassEServer
{
publicstaticvoidmain(Stringargs[])
{
ServerSocket
s=null;Stringline;Da
taInputStream
is;PrintStream
ps;Socketc=null;
try
{
s=newServerSocket(9000);
}
catch(IOExceptione)
{
System.out.println(e);
}
try
{
c=s.accept();
is=newDataInputStream(c.getInputStream());
20
ps=newPrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();ps.println(line
);
}
}
catch(IOExceptione)
{
System.out.println(e);
}
}
}

EClient.java
importjava.net.*;
importjava.io.*;
publicclassEClient
{ publicstaticvoidmain(Stringarg[])
{
Socket
c=null;Stringli
ne;
DataInputStreamis,is1;
PrintStreamos;
try
{
InetAddressia=InetAddress.getLocalHost();c
=new Socket(ia,9000);
}
Catch (IOExceptione)
{
System.out.println(e);
}
try
{
os=newPrintStream(c.getOutputStream());i
s=newDataInputStream(System.in);
is1=newDataInputStream(c.getInputStream());
while(true)
{
System.out.println("Client:");line=is.readL
ine();
21
os.println(line);
System.out.println("Server:"+is1.readLine());
}
}
catch(IOExceptione)
{
System.out.println("SocketClosed!");
}
}}
OUTPUT
Server
C:\ProgramFiles\Java\jdk1.5.0\
bin>javacEServer.javaC:\Program Files\Java\jdk1.5.0\
bin>java EServerC:\ProgramFiles\Java\jdk1.5.0\bin>
Client
C:\ProgramFiles\Java\jdk1.5.0\
bin>javacEClient.javaC:\Program Files\Java\jdk1.5.0\
bin>java EClientClient:
HaiServer
Server:
HaiServerClient:
HelloServer:
HelloClient:end
Server:endClient:
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 tostep10
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 from3to8
10. Stop
Server
1. Start
2. Create UDP datagram socket, make listening socket
3. Receive the request message sent by the client
4. If the received message is“END” go tostep10
5. Retrieve the client’sIPaddress 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 from3to8.
10. Stop.

PROGRAM
UDPserver.java
importjava.io.*;
importjava.net.*;
class UDP server
{
Public static Datagram Socketds;
Public static byte buffer[]=new
byte[1024];publicstaticintclientport=789,server
port=790;
Public static void main(Stringargs[])throwsException
{
ds=new
DatagramSocket(clientport);System.out.println("press
ctrl+ctoquittheprogram");
BufferedReaderdis=newBufferedReader (newInputStreamReader (System.in));
InetAddressia=InetAddress.geyLocalHost ();
while(true)
{
DatagramPacketp=new
DatagramPacket(buffer,buffer.length);ds.receive(p);
Stringpsx=newString(p.getData(),0,p.getLength());
System.out.println("Client:" +
psx);System.out.println("Server:");
Stringstr=dis.readLine();i
f(str.equals("end"))
break;buffer=str
.getBytes();
ds.send(newDatagramPacket(buffer,str.length(),ia,serverport));
}
}
}
UDPclient.javai
mport
java .io.*;import
java.net.*;classU
DPclient
{
publicstaticDatagramSocketds;
publicstaticintclientport=789,serverport=790;
publicstaticvoid main(Stringargs[])throwsException
{
bytebuffer[]=newbyte[1024];ds=new
DatagramSocket(serverport);
BufferedReaderdis=newBufferedReader (newInputStreamReader (System.in));
System.out.println ("serverwaiting");
InetAddress
ia=InetAddress.getLocalHost();while(true)
{
System.out.println("Client:");Str
ing
str=dis.readLine();if(str.equals("
end"))
break;buffer=str
.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
DatagramPacketip=new
DatagramPacket(buffer,buffer.length);ds.receive(p);
Stringpsx=newString (p.getData(),0,p.getLength());
System.out.println("Server:"+ psx);
}
}}

OUTPUT:
Server
C:\Program Files\Java\jdk1.5.0\bin>javac
UDPserver.javaC:\ProgramFiles\Java\jdk1.5.0\bin>java
UDPserver
pressctrl+ctoquittheprogramCli
ent:HaiServer
Server:Hello
ClientClient:How
are
YouServer:IamFine
Client
C:\ProgramFiles\Java\jdk1.5.0\bin>javacUDPclient.javaC:\Program Files\Java\jdk1.5.0\bin>java
UDPclientserverwaiting
Client:Hai
ServerServer:Hello
ClieClient:How are
YouServer:I am
FineClient:end

RESULT:

Thus the java application program using TCP Sockets was developed and executed
successfully
Ex.No:4 Simulation of DNS using UDP Sockets

AIM
To write a java program for DNS application

PRELABDISCUSSION:

 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.
 Thedomainnamespacerefersahierarchyintheinternetnamingstructure.Thishierarchy 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
maintainentireDNSdatabase,therefore,theinformationisdistributedamongmanyDNSserver
 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 divide
into three different sections: generic domains, country domains, and inverse domain.
 The main function of DNS is to translate domainnames into IPAddresses, 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 hostname and IP address
4. Receive the hostname from the client
5. Retrieve the client’s IP address from the received datagram
6. Get the IPaddress mapped for the hostname from the table.
7. Display the hostname and corresponding IPaddress
8. Send the IPaddress for the requested hostname to the client
9. Stop.
Client
1. Start
2. Create UDP datagram socket.
3. Get the hostname from the client
4. Send the hostname to the server
5. Wait for the reply from the server
6. Receive the reply datagram and read the IPaddress for the requested host name
7. Display the IP address.
8. Stop.

PROGRAM
DNSServer
javaimportjava.io.*;
importjava.net.*;
publicclassudpdnsserver
{
privatestaticintindexOf(String[]array,Stringstr)
{
str=str.trim();
for(inti=0;i<array.length;i++)
{
if
(array[i].equals(str))re
turni;
}
return-1;
}
publicstaticvoidmain(Stringarg[])throwsIOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com",
"facebook.com"};String[]ip={"68.180.206.184","209.85.148.19","80.168.92.140","6
9.63.189.16"};
System.out.println("PressCtrl+CtoQuit");wh
ile(true)
{
DatagramSocket serversocket=new
DatagramSocket(1362);byte[]senddata= newbyte[1021];
byte[] receivedata=newbyte[1021];
DatagramPacketrecvpack=newDatagramPacket(receivedata,receivedata.length);ser
versocket.receive(recvpack);
Stringsen=newString(recvpack.getData());
InetAddressipaddress=recvpack.getAddress();i
ntport= recvpack.getPort();
Stringcapsent;
System.out.println("Request
forhost"+sen);if(indexOf(hosts,sen)!=-1)
capsent=ip[indexOf(hosts,sen)];
else
capsent="HostNotFound";
senddata=capsent.getBytes();
DatagramPacketpack=newDatagramPacket(senddata,senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}}}
UDP DNS Client
java
importjava.io.*;
importjava.net.*;
publicclassudpdnsclient
{
publicstaticvoid main(Stringargs[])throwsIOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));DatagramSocketclientsocket= new
DatagramSocket();
InetAddressipaddress;i
f(args.length==0)
ipaddress=InetAddress.getLocalHost();
else
ipaddress=InetAddress.getByName(args[0]);b
yte[]senddata = newbyte[1024];
byte[]receivedata=newbyte[1024];in
tportaddr=1362;
System.out.print("Enterthehostname:");St
ringsentence = br.readLine();
Senddata=sentence.getBytes();
DatagramPacketpack=newDatagramPacket(senddata,senddata.length,
ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacketrecvpack=newDatagramPacket(receivedata,receivedata.length);cl
ientsocket.receive(recvpack);
Stringmodified=newString(recvpack.getData());S
ystem.out.println("IP Address: " +
modified);clientsocket.close();
}}

OUTPUT
Server
javacudpdnsserver.javaj
ava udpdnsserver
Press Ctrl + C to Quit Request for host
yahoo.comRequestforhostcricinfo.com
Requestforhostyoutube.com

Client
>javacudpdnsclient.java
>javaudpdnsclient
Enter the hostname :
yahoo.comIPAddress:68.180.20
6.184
>javaudpdnsclient
Enter the hostname :
cricinfo.comIPAddress:80.168.92
.140
>javaudpdnsclient
Enterthehostname:youtube.comIP
Address: Host NotFound

RESULT:
Thus the java application program using UDP Sockets to implement DNS was developed and
executed successfully
Ex.No:6 Write a code simulating ARP/RARP protocols

AIM:

To write a java program for simulating ARP and RARP protocols using TCP.

PRELABDISCUSSION:

 Address Resolution Protocol(ARP) is a low-level network protocol for translating


network layer addresses into link layer addresses.ARP lies between layers 2 and 3 of the
OSI model, although ARP was not included in the OSI framework and allows computers
to introduce each other across a network prior to communication. Because protocols are
basic network communication units, address resolution is dependent on protocols such as
ARP, which is the only reliable method of handling required tasks.
 The Address Resolution Protocol (ARP) is a communication protocol used for
discovering the link layer address, such as a MAC address, associated with a given
internet layer address,
 When configuring a new network computer, each system is assigned an Internet
Protocol(IP) address for primary identification and communication. A computer also has
a unique media access control (MAC) address identity. Manufacturers embed the MAC
address in the local area network (LAN) card. The MAC address is also known as the
computer’s physical address.
 Address Resolution Protocol (ARP) is used to resolve an IPv4 address (32 bit Logical
Address) to the physical address (48 bit MAC Address). Network Applications at the
Application Layer use IPv4Addresstocommunicate with an other device.
 Reverse Address Resolution Protocol (RARP)is a network protocol used to resolve a
datalink layer address to the corresponding network layer address. For example,
RARP is used to resolve a Ethernet MAC address to an IPaddress.
 The client broadcasts a RARP packet with an Ethernet broadcast address, and it's own
physical address in the data portion. The server responds by telling the client it's IP
address. Note there is no name sent. Also note there is no security.
 Media Access Control (MAC) addresses need to be individually configured ontheservers
by an administrator. RARP is limited to serving only IP addresses.Reverse
ARPdiffersfromtheInverseAddressResolutionProtocolwhichisdesignedtoobtaintheIP
Address associatedwithalocalFrameRelaydatalinkconnectionidentifier.InARPisnot
Used in Ethernet.
ALGORITHM:
Client

1. Start the program


2. Create socket and establish connection with the server.
3. Get the IPaddress to be converted into MAC address from the user.
4. Send this IPaddress to server.
5. Receive the MAC address for the IPaddress from the server.
6. Display the received MAC address
7. Terminate the connection

Server

1. Start the program


2. Create the socket, bind the socket created with IPaddress and port number and make it a
listening socket.
3. Accept the connection request when it is requested by the client.
4. ServermaintainsthetableinwhichIPandcorrespondingMACaddressesarestored.
5. Receive the IPaddress sent by the client.
6. Retrieve the corresponding MAC address for the IPaddress and send it to the client.
7. Closetheconnectionwiththeclientandnowtheserverbecomesalisteningserverwaitingf
orthe connection request from other clients
8. Stop the program

PROGRAM
Client:
importjava.io.*;
Importjava.net.*;
importjava.util.*;
classClientarp
{
publicstaticvoidmain(Stringargs[])
{
try
{
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));Socketc
lsct=newSocket("127.0.0.1",139)
DataInputStream din=new
DataInputStream(clsct.getInputStream());DataOutputStreamdout=newDat
aOutputStream(clsct.getOutputStream());System.out.println("EntertheLogi
caladdress(IP):");
Stringstr1=in.readLine();d
out.writeBytes(str1+'\
n';Stringstr=din.readLine(
);

34
System.out.println("ThePhysicalAddressis:"+str);clsct.clos
e();
}
catch(Exceptione)
{
System.out.println(e);
}}
}

Server:
importjava.io.*;
import java.net.*;
importjava.util.*;
classServerarp
{
publicstaticvoidmain(Stringargs[])
{
try{
ServerSocket
obj=newServerSocket(139
);
Socketobj1=obj.accept();
while(true)
{
DataInputStream din=new
DataInputStream(obj1.getInputStream());DataOutputStream dout=new
DataOutputStream(obj1.getOutputStream());Stringstr=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
Stringmac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(inti=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\
n');break;
}
}
obj.close();
}
}
catch(Exceptione)
{
System.out.println(e);
}}
}
Output:
E:\networks>java
ServerarpE:\networks>java
ClientarpEntertheLogicaladdr
ess(IP):
165.165.80.80
ThePhysicalAddressis:6A:08:AA:C2

(b) Program for Reverse Address Resolution Protocol(RARP) using UDP

ALGORITHM:

Client
1. Start the program
2. Create datagram socket
3. Get the MACaddress to be converted into IPaddress from the user.
4. Send this MACaddress to server using UDP datagram.
5. Receive the datagram from the server and display the corresponding IP address.
6. Stop the program

Server
1. Start the program.
2. ServermaintainsthetableinwhichIPandcorrespondingMACaddressesarestored.
3. Create the datagram socket
4. Receive the datagram sent by the client and read the MAC address sent.
5. Retrieve the IP address for the received MAC address from the table.
6. Display the corresponding IPaddress.
7. Stop the program

PROGRAM:
Client:
importjava.io.*;
importjava.net.*;
import java.util.*;
classClientrarp12
{
publicstaticvoidmain(Stringargs[])
{
try
{
DatagramSocketclient=new
DatagramSocket();InetAddressaddr=InetAddress.getBy
Name("127.0.0.1");byte[]sendbyte=newbyte[1024];
byte[]receivebyte=newbyte[1024];
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Enterthe Physicaladdress(MAC):")
Stringstr=in.readLine();sendbyte=str.getBytes();
DatagramPacket sender=newDatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacketreceiver=newDatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
Strings=newString(receiver.getData());System.out.println("The
LogicalAddressis(IP):"+s.trim());client.close();

}
catch(Exceptione)
{
System.out.println(e);
}}}
Server:
importjava.io.*;
importjava.net.*;
import java.util.*;
classServerrarp12
{
publicstaticvoidmain(Stringargs[])
{
try{
DatagramSocketserver=newDatagramSocket(1309);
while(true)
{
byte[]sendbyte=newbyte[1024];byt
e[]receivebyte=newbyte[1024];
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);server.receive(receiver);
Stringstr=newString(receiver.getData());
Strings=str.trim();
InetAddressaddr=receiver.getAddress();i
ntport=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
Stringmac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(inti=0;i<ip.length;i++)
{
if(s.equals(mac[i]))
{
sendbyte=ip[i].getBytes();Dat
agramPacketsender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
break;
}}}catch(Exceptione)
{
System.out.println(e);
}}}
Output:
I:\
ex>javaServerrarp12I:\
ex>javaClientrarp12
EnterthePhysicaladdress(MAC):6
A:08:AA:C2
TheLogicalAddressis(IP):165.165.80.80

RESULT:
Thus the program for implementing to display simulating ARP and RARP protocols was
executed successfully and output is verified.
Ex.No:7 Study of Network simulator (NS) and Simulation of Congestion Control
Algorithms using NS

AIM:
To Study Network simulator (NS) and Simulation of Congestion Control Algorithms
Using NS

PRE LAB DISCUSSION:

NETWORK SIMULATOR (NS2)


Ns Overview

Ns Status

Periodical release (ns-2.26,Feb2003)

Platform support

FreeBSD, Linux, Solaris, Windows and Mac
Ns functionalities
Routing, Transportation, Traffic sources, Queuing disciplines, QoS
Congestion Control Algorithms
 Slow start
 Additive increase/multiplicative decrease
 Fast retransmit and Fast recovery
Case Study: Asimple Wireless network.
Ad hoc routing, mobile IP, sensor-
MACTracing, visualizationn and various
utilitie NS (NetworkSimulators)
Most of the commercial simulators are GUI driven, while some network simulators are
CLI driven. The network model / configuration describes the state of the network (nodes, routers,
switches, links) and the events (data transmissions, packet error etc.). Important outputs of
simulations are the trace files. Trace files log every packet, every event that occurred in the
simulation and are used for analysis. Network simulators can also provide other tools to facilitate
visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation ,in which a list of pending"events"
is stored, and those events are processed in order, with some events triggering future events—
such as the event of the arrival of a packet at one node triggering the event of the arrival of that
packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high, then
estimation of the average occupancy is challenging because of high variance. To estimate the
likelihood of a buffer overflow in a network, the time required for an accurate answer can be
extremely large. Specialized techniques such as "control variates" and "importance sampling"
have been developed to speed simulation.
Examples of network simulators
There are many both free/open-source and proprietary network simulators. Examples of
notable network simulation s oftware are, ordered after how often they are mentioning in
research papers:
1. ns(open source)
2. OPNET(proprietary software)
3. NetSim(proprietary software)
Uses of network simulators
Network simulators serve a variety of needs. Compared to the cost and time involved in
setting up an entire test bed containing multiple networked computers, routers and data links,
network simulators are relatively fast and inexpensive. They allow engineers, researchers to test
scenarios that might be particularly difficult or expensive to emulate using real hardware – for
instance, simulating a scenario with several nodes or experimenting with a new protocol in
thenetwork.Networksimulatorsareparticularlyusefulinallowingresearcherstotestnewnetworkingpr
otocolsorchangestoexistingprotocolsinacontrolledandreproducibleenvironment. A typical
network simulator encompasses a wide range of networking technologies and can help the users
to build complex networks from basic building blocks such as a variety of nodes and links. With
the help of simulators, one can design hierarchical networks using
varioustypesofnodeslikecomputers,hubs,bridges,routers,switches,links,mobileunitsetc.
Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and
Local Area Network(LAN) technologies like Ethernet, token rings etc.,can all be simulated with
atypical simulator and the user can test, analyze various standard results apart from devising
some novel protocol or strategy for routing etc. Network simulators are also widely used to
simulate battle field networks in Network-centric warfare.
There are a wide variety of network simulators, ranging from the very simple to the very
complex. Minimally, a network simulator must enable a user to represent a network topology,
specifying the nodes on the network, the links between those nodes and the traffic between the
nodes. More complicated systems may allow the user to specify everything about the protocols
used to handle traffic in a network. Graphical applications allow users to easily visualize the
workings of their simulated environment. Text-based applications may provide a less intuitive
interface,but may permit more advanced forms of customization.

Packetloss
Packetloss occurs when one or more packets of data travelling across a computer network
fail to reach their destination. Packet loss is distinguished as one of the three main error types
encountered in digital communications; the other two being bit error and spurious packets caused
due to noise.
Packets can be lost in a network because they may be dropped when a queue in the
network node overflows. The amount of packet loss during the steady state is another important
property of a congestion control scheme. The larger the value of packet loss, the more difficult
itisfortransportlayerprotocolstomaintainhighbandwidths,thesensitivitytolossofindividual
Packets,aswellastofrequencyandpatternsoflossamonglongerpacketsequencesisstronglydependentontheap
plicationitself.

Throughput
Throughput is the main performance measure characteristic, and most widely used. In
communication networks, such as Ethernet or packet radio, throughput or network throughput is
the average rate of successful message delivery over a communication channel. Throughput is
usually measured bits per second (bit/s orbps), and sometimes in data packets per second or data
packets per time slot. These measures how soon the receiver is able to get a certain amount of
data send by the sender. It is determined as the ratio of the total data received to the end to end
delay. Throughput is an important factor which directly impacts then network performance.

Delay
Delay is the time elapsed while a packet travels from one point e.g., source premise or
Network ingress to destination premise or network degrees. The larger the value of delay, the
more difficult it is for transport layer protocols to maintain high bandwidths. We will calculate
endtoend delay

Queue Length
A queuing system in networks can be described as packets arriving for service, waiting for
service if it is not immediate, and if having waited for service, leaving the system after being
served. Thus queue length is very important characteristic to determine that how well the active
queue management of the congestion control algorithm has been working.

Congestion control Algorithms


Slow-start is used in conjunction with other algorithms to avoid sending more data than the
network is capable of transmitting, that is, to avoid causing network congestion. The additive
increase/multiplicative decrease (AIMD) algorithm is a feedback control algorithm. AIMD
combines linear growth of the congestion window with an exponential reduction when a
congestion takes place. Multiple flows using AIMD congestion control will eventually converge
to use equal amounts of a contended link. Fast Retransmit is an enhancement to TCP that reduces
the time a sender waits before retransmitting a lost segment.

Program:
Include<wifi_lte/
wifi_lte_rtable.h>structr_hist_entr
y*elm,*elm2;
intnum_later =1;
elm=STAILQ_FIRST(&r_hist_);
while(elm!=NULL&&num_later <=num_dup_acks_)
{num_later;
elm=STAILQ_NEXT(elm,linfo_);
}

if(elm!=NULL){
elm=findDataPacketInRecvHistory(STAILQ_NEXT(elm,linfo_));

if(elm!= NULL){
elm2=STAILQ_NEXT(elm,
linfo_);while(elm2!=NULL){
if(elm2->seq_num_< seq_num&&elm2->t_recv_<
time){

STAILQ_REMOVE(&r_hist_,elm2,r_hist_entry,linfo_);del
ete elm2;
}else
elm= elm2;
elm2=STAILQ_NEXT(elm,linfo_);
}
}
}
}
void DCCPTFRCAgent::removeAcksRecvHistory()
{structr_hist_entry*elm1=STAILQ_FIRST(&r_hist_);stru
ctr_hist_entry*elm2;

intnum_later =1;
while(elm1!=NULL &&num_later<=num_dup_acks_)
{num_later;
elm1=STAILQ_NEXT(elm1,linfo_);
}

if(elm1==NULL)
return;

elm2=STAILQ_NEXT(elm1,
linfo_);while(elm2!=NULL){
if (elm2->type_ == DCCP_ACK)
{STAILQ_REMOVE(&r_hist_,elm2,r_hist_entry,linfo_);de
lete elm2;
}else{
elm1=elm2;
}
elm2=STAILQ_NEXT(elm1,linfo_);
}
}
inline r_hist_entry
*DCCPTFRCAgent::findDataPacketInRecvHistory(r_hist_entry *start)
{while(start!= NULL&&start->type_== DCCP_ACK)
start=STAILQ_NEXT(start,linfo_);r
eturnstart;
}

Result:
Thus we have Studied Network simulator (NS) and Simulation of Congestion Control
Algorithms using NS.
Ex.No:8 Study of TCP/UDP performance using Simulation tool.

AIM:

To simulate the performance of TCP/UDP using NS2.

PRELABDISCUSSION:

 TCP is reliable protocol. That is, the receiver always sends either positive or negative
acknowledgement about the data packet to the sender, so that the sender always has
bright clue about whether the data packet is reached the destination or it needs to resend
it.
 TCP ensures that the data reach unintended destination in the same order it was sent.
 TCP is connection oriented .TCP requires that connection between two remote points be
established before sending actual data.
 TCP provides error-checking and recovery mechanism.
 TCP provide send-to-end communication.
 TCP provides flow control and quality of service.
 TCP operates in Client/Server point-to-point mode.
 TCPprovidesfullduplexserver,i.e.itcanperformrolesofbothreceiverandsender.
 The User Datagram Protocol (UDP) is simplest Transport Layer communication protocol
vailable of the TCP/IP protocol suite. It involves minimum amount of communication
mechanism. UDP is said to be an unreliable transport protocol but it uses IP services
which provides best effort delivery mechanism.UDP is used when acknowledgement of
data does not hold any significance.
 UDP is good protocol for data flowing in one direction.
 UDP is simple and suitable for query based communications.
 UDP is not connection oriented.
 UDP does not provide congestion control mechanism.
 UDP does not guarantee ordered delivery of data.
 UDP is stateless.
 UDP is suitable protocol for streaming applications such asVoIP, multimedia streaming .
TCP Performance
Algorithm
1. Create a Simulator object.
2. Set routing as dynamic.
3. Open the trace and namtracefiles.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the tcp agent.
8. Connect tcp and tcp sink.
9. Run the simulation.

PROGRAM:

setns[newSimulator]
$nscolor0Blue
$nscolor 1Red
$nscolor2Yellows
et n0 [$ns node]set
n1 [$ns node]set
n2 [$ns
node]setn3[$nsnod
e]
setf[opentcpout.tr w]
$nstrace-all$f
setnf[open tcpout.namw]
$nsnamtrace-all$nf
$nsduplex-link$n0$n25Mb2msDropTail
$nsduplex-link$n1$n25Mb2msDropTail
$nsduplex-link$n2$n31.5Mb10msDropTail
$nsduplex-link-op$n0$n2orientright-up
$nsduplex-link-op$n1$n2orientright-down
$ns duplex-link-op$n2$n3orientright
$nsduplex-link-
op$n2$n3queuePos0.5settcp[newAgent/
TCP]
$tcpsetclass_1
setsink[newAgent/TCPSink]
$nsattach-agent$n1$tcp
$nsattach-agent$n3$sink
$ns connect$tcp$sink
setftp[newApplication/FTP]
$ftpattach-agent$tcp
$nsat1.2 "$ftpstart"
$nsat1.35"$nsdetach-agent$n1$tcp;$nsdetach-agent$n3$sink"
$nsat3.0"finish"p
rocfinish{}{
globalnsfnf
$ns flush-
traceclose$f
close$nf
puts"Runningnam.."
execxgraphtcpout.tr-geometry600x800
&execnamtcpout.nam&
exit0
}
$nsrun

Output
UDPPerformance

ALGORITHM:

1. Create a Simulator object.


2. Set routing as dynamic.
3. Open the trace and namtrace iles.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the UDP agent.
8. Connect udp and null agents.
9. Run the simulation.

PROGRAM:
setns[newSimulator]
$nscolor0Blue
$nscolor1Red
$nscolor2Yellows
et n0 [$ns node]set
n1 [$ns node]set
n2 [$ns
node]setn3[$nsnod
e]
setf[openudpout.trw]
$nstrace-all$f
setnf[open udpout.namw]
$nsnamtrace-all$nf
$nsduplex-link$n0$n25Mb2msDropTail
$nsduplex-link$n1$n25Mb2msDropTail
$nsduplex-link$n2$n31.5Mb10msDropTail
$nsduplex-link-op$n0$n2orientright-up
$nsduplex-link-op$n1$n2orientright-down
$ns duplex-link-op$n2$n3orientright
$nsduplex-link-
op$n2$n3queuePos0.5setudp0 [new
Agent/UDP]
$nsattach-agent$n0$udp0
setcbr0[newApplication/Traffic/CBR]
$cbr0 attach-agent
$udp0setudp1[newAgent/$
]nsattach-agent$n3$udp1
$udp1setclass_0
setcbr1[newApplication/Traffic/CBR]
$cbr1 attach-agent
$udp1setnull0[newAgnull
$nsattach-
agent$n1$null0setnull1[ne
wAgent/Null]
$nsattach-agent$n1$null1
$nsconnect$udp0$null0
$nsconnect$udp1$null1
$nsat1.0"$cbr0start"
$nsat1.1 "$cbr1start"
puts[$cbr0setpacketSize_]p
uts[$cbr0setinterval_]
$nsat3.0"finish"p
rocfinish{}{
globalnsfnf
$ns flush-
traceclose$f
close$nf
puts "Running
nam.."execnamudpout.n
am&exit0
}$nsrun

Output:

RESULT:

Thus the study of TCP/UDP performance is done successfully.


Ex.No:9 Simulation of Distance Vector / Link State Routing algorithm.

AIM:

To simulate the Distance vector and link state routing protocols usingNS2.

PRELABDISCUSSION:

LINKSTATEROUTING
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
functionismuchbetterdescribedassimplyforwarding.Routingisperformedformanykindsofnetworks,
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 usingpacketswitchingtechnology.
In packet switching networks, routing directs packet forwarding (the transit of
logicallyaddressednetworkpacketsfromtheirsourcetowardtheirultimatedestination)throughinterme
diate 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:wherelongersubnetmasksarepreferred(independentofwhetheritiswithina
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) out
perform sun structured addressing(bridging).Routing has become he dominant form of
addressing on the Internet. Bridging is still widely used within localized environments.
b. Flooding
Flooding is 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 fat
allow of flooding. All nodes have neighbors and route packets indefinitely. More than two
neighbors creates abroad cast 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.

Distance vector Routing:


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
thenodesinanetworkoftopologychanges,distance-
vectorroutingprotocolshavelesscomputationalcomplexityandmessage overhead.
The term distance vector refers to the fact that the protocol manipulates vectors (arrays)of
distances to other nodes n 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
RIPv2andIGRP.

Method
Routersusingdistance-
vectorprotocoldonothaveknowledgeoftheentirepathtoadestination.Insteadtheyusetwo 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
theroutewithminimumdistance.Eachnodemaintainsavector(table)ofminimumdistanceto
Every node. The cost of reaching a destination is calculated using various 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
arouter'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
itis 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 actually
valid and true. There are a number of features which can be used to help with instability and in
accurate 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).

ALGORITHM:

1. Create a Simulator object.


2. Set routing as dynamic.
3. Open the trace and namtracefiles.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the udp agent.
8. Connect udp and null..
9. At1secthelinkbetweennode1and2isbroken.
10. At2secthelinkisupagain.
11. Run the simulation.
LINK STATE ROUTING PROTOCOL

PROGRAM
setns[newSimulator]
$nsrtprotoLS
setnf[openlinkstate.namw]
$nsnamtrace-all$nf
setf0[openlinkstate.trw]
$ns trace-all
$f0procfinish{}
{
globalnsf0nf
$ns flush-
traceclose$f0
close$nf
execnamlinkstate.nam&e
xit0
}
for{seti0}{$i<7}{incr i}
{setn($i)[$nsnode]
}
for{seti0}{$i<7}{incr i}{
$ns duplex-link$n($i)$n([expr($i+1)%7])1Mb10msDropTail
}
setudp0[newAgent/UDP]
$nsattach-agent$n(0)$udp0
setcbr0[newApplication/Traffic/CBR]
$cbr0setpacketSize_500
$cbr0setinterval_0.005
$cbr0 attach-agent
$udp0setnull0[newAgent/
Null]
$nsattach-agent$n(3)$null0
$nsconnect$udp0$null0
$nsat0.5"$cbr0 start"
$nsrtmodel-at1.0down$n(1)$n(2)
$nsrtmodel-at2.0up$n(1)$n(2)
$nsat4.5"$cbr0stop"
$nsat5.0"finish"
$nsrun

Output:

54
DISTANCEVECTORROUTINGALGORITHM

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. AddUDPagentfornoden1
9. Create CBR traffic ontop of UDP and set traffic parameters.
10. Addasinkagenttonoden4
11. Connect source and the sink
12. Schedule events as follows:
a. Start traffic flowat0.5
b. Down the linkn3-n4 at1.0
c. Up the link n3-n4at2.0
d. Stoptrafficat3.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 asimulatorobject
setns[newSimulator]
#Usedistancevectorrouting
$nsrtprotoDV
#Openthenamtracefilese
tnf[openout.namw]
$nsnamtrace-
all$nf#Opentracefil
e
setnt[opentrace.trw]
$nstrace-all$nt
#Define'finish'procedure
procfinish{}
{
globalnsnf
$nsflush-
trace#Closethetrace
fileclose $nf
#Executenamonthetracefileex
ec nam-aout.nam&
exit0
}
# Create 8
nodesset 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]setn8[$nsn
ode]
#Specifylinkcharacterestics
$nsduplex-link$n1$n21Mb10msDropTail
$nsduplex-link$n2$n31Mb10msDropTail
$nsduplex-link$n3$n41Mb10msDropTail
$nsduplex-link$n4$n51Mb10msDropTail
$nsduplex-link $n5$n6 1Mb10msDropTail
$nsduplex-link$n6$n71Mb10msDropTail
$nsduplex-link$n7$n81Mb10msDropTail
$nsduplex-
link$n8$n11Mb10msDropTail#specifylayout
as a octagon
$nsduplex-link-op$n1$n2orientleft-up
$nsduplex-link-op$n2$n3orientup
$nsduplex-link-op$n3$n4orientright-up
$nsduplex-link-op$n4$n5orientright
$nsduplex-link-op$n5$n6orientright-down
$nsduplex-link-op$n6$n7orientdown
$nsduplex-link-op$n7$n8orientleft-down
$nsduplex-link-op $n8 $n1orientleft#Create
a UDP agent and attach it to node
n1setudp0[new Agent/UDP]
$nsattach-agent$n1$udp0
#CreateaCBRtrafficsourceandattach it toudp0
setcbr0[newApplication/Traffic/CBR]
$cbr0setpacketSize_500
$cbr0setinterval_0.005
$cbr0attach-agent$udp0
#CreateaNullagent(atrafficsink) andattach itto
noden4setnull0[newAgent/Null]
$nsattach-agent$n4$null0
#Connectthetrafficsourcewiththetrafficsink
$nsconnect$udp0$null0
#Scheduleevents fortheCBRagentandthenetworkdynamics
$nsat0.0"$n1 labelSource"
$nsat0.0"$n4labelDestination"
$nsat0.5"$cbr0 start"
$nsrtmodel-at1.0down$n3$n4
$nsrtmodel-at2.0up$n3$n4
$nsat4.5 "$cbr0stop"
#Callthefinishprocedureafter 5 secondsofsimulationtime
$nsat5.0"finish"#Ru
nthesimulation
$nsrun

OUTPUT
$nsdistvect.tcl
RESULT:

Thus the simulation for Distance vector and link state routing protocols was done using
NS2.
Ex.No:10 Simulation of Error Detection Code (like CRC)

AIM:
To implement error checking code using java.

PRELAB DISSCUSSION:

The cyclic redundancy check, or CRC, is a technique for detecting errors in digital data, but
not form a king corrections when errors are detected. It is used primarily in data transmission.
In the CRC method, a certain number of check bits, often called a checksum, are appended to
the message being transmitted. The receiver can determine whether or not the check bits agree with
the data, to ascertain with a certain degree of probability whether or not an error occurred in
transmission.
CRC involves binary division of the data bits being sent by a predetermined divisor agreed
upon by the communicating system. The divisor is generated using polynomials. So, CRC is also
called polynomial code checksum.
CRC uses Generator Polynomial which is available on both sender and receiver side. An
example generator polynomial is of the form like x3 + x + 1. This generator polynomial
representskey1011.Anotherexampleisx2+1thatrepresentskey101.
Sender Side (Generation of Encoded Data from Data and Generator Polynomial(or Key)):
 Thebinarydataisfirstaugmentedbyaddingk-1zerosintheendofthedata
 Usemodulo-
2binarydivisiontodividebinarydatabythekeyandstoreremainderofdivi
sion.
 Append the remainder at the end of the data to form the encoded data and send the same

Receiver Side(Check if there are errors introduced in transmission)

Performmodulo-2 division again and if remainder is 0,then there are no errors.

Modulo2Division:

 Theprocessofmodulo-
2binarydivisionisthesameasthefamiliardivisionprocessweusefordecimalnumbers.Justthatinste
adofsubtraction,weuseXORhere.
 In each step, a copy of the divisor(or data)is XOR ed with the k bits of the dividend(or key).
 TheresultoftheXORoperation(remainder)is(n-
1)bits,whichisusedforthenextstepafter1extrabitispulleddowntomakeitnbitslong.
 Whentherearenobitslefttopulldown,wehavearesult.The(n-1)-
bitremainderwhichisappendedatthesenderside.
ALGORITHM:

1. Start the Program


2. Given a bit string, append0 S to the end of it(thenumberof0sisthesameasthedegreeofthe
generate or polynomial) letB (x)be the polynomial corresponding to B.
3. DivideB(x)bysomeagreedonpolynomialG(x)
(generatorpolynomial)anddeterminetheremainderR(x).ThisdivisionistobedoneusingModul
o2Division.
4. Define T(x)=B(x)–R(x)
5. (T(x)/G(x)=>remainder0)
6. Transmit T,the bit string corresponding to T(x).
7. Let T’ represent the bit stream the receiver gets and T’(x) the associated polynomial. The
receiver divides T1(x) by G(x). If there is a 0 remainder, the receiver concludes T = T’
and no error occurred otherwise, the receiver concludes an error occurred and requires
are transmission
8. Stop the Program

PROGRAM:

importjava.io.*;
classcrc_gen
{
publicstaticvoidmain(Stringargs[])throwsIOException{
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));in
t[]data;
int[]div;int[]
divisor;int[]
rem;
int[] crc;
intdata_bits,divisor_bits,tot_length;
System.out.println("Enternumberofdatabits:");data_bits=Integer.parseInt(br.readLine());data=newin
t[data_bits];
System.out.println("Enter data bits :
");for(inti=0;i<data_bits; i+
+)data[i]=Integer.parseInt(br.readLine(
));
System.out.println("Enternumberofbitsindivisor:");divisor_bits=Integer.parseInt(br.rea
dLine()); divisor=newint[divisor_bits];System.out.println("EnterDivisorbits:");
for(inti=0; i<divisor_bits;i+
+)divisor[i]=Integer.parseInt(br.readLine(
));System.out.print("Databitsare:");for(int
i=0;i< data_bits; i+
+)System.out.print(data[i]);System.out.pr
intln();
System.out.print("divisor bits are :
");for(inti=0;i<divisor_bits; i+
+)System.out.print(divisor[i]);System
.out.println();
*/
tot_length=data_bits+divisor_bits-
1;div=newint[tot_length];
rem=newint[tot_length];
crc=newint[tot_length];
/* CRCGENERATION
*/for(inti=0;i<data.length;i++)
div[i]=data[i];
System.out.print("Dividend(afterappending0's)are:");for(int i=0;i<div.length;i++)System.out.print(div[i]);
System.out.println();
for(intj=0;j<div.length;j++)
{rem[j]= div[j];
}
rem=divide(div,divisor,rem);f
or(inti=0;i<div.length;i++)
{

//

appenddividendandremaindercrc

[i]=(div[i]^rem[i]);
}
System.out.println();System.out.pr
intln("CRC code :
");for(inti=0;i<crc.length;i+
+)System.out.print(crc[i]);

/* ERRORDETECTION
*/System.out.println();
System.out.println("EnterCRCcodeof"+tot_length+"bits:");for(inti=0;i<crc.length;i+
+)crc[i]=Integer.parseInt(br.readLine());
System.out.print("crc bits are :
");for(inti=0;i< crc.length;i+
+)System.out.print(crc[i]);System
.out.println();
for(intj=0;j<crc.length;j++)
{rem[j]= crc[j];
}
rem=divide(crc, divisor,
rem);for(inti=0;i<rem.length;i
++)
{
if(rem[i]!=0)
{
System.out.println("Error");b
reak;
}
if(i==rem.length-
1)System.out.println("NoError"
);
}
System.out.println("THANKYOU.......)");
}
staticint[]divide(intdiv[],intdivisor[],intrem[])
{
intcur=0;w
hile(true)
{
for(inti=0;i<divisor.length;i+
+)rem[cur+i]=(rem[cur+i]^divisor[i]);whil
e(rem[cur]==0 && cur!=rem.length-1)cur+
+;
if((rem.length-
cur)<divisor.length)break;
}
returnrem;
}
}
OUTPUT:
Enternumberofdata bits:
7
Enter databits:
1
0
1
1
0
0
1
Enter number ofbitsindivisor :
3
EnterDivisor bits:
1
0
1
Dividend (after appending 0's) are :
101100100CRCcode:
101100111
Enter CRCcodeof9bits:1
0
1
1
0
0
1
0
1
crc bits are :
101100101Error
THANKYOU.......)
BUILDSUCCESSFUL(totaltime:1minute34seconds)

RESULT:
Thus the above program for error checking code using was executed successfully.
TOPIC BEYOND SYLLABUS

Ex.No:11 Performance Evaluation of Routing protocols using Simulation tool.

(a) UNICASTROUTINGPROTOCOL

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

PRELAB DISCUSSION:

 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
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 route 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
canmakedecisionbasedonthefollowinginformation.Routescanbestaticallyconfigure
d 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 orunicast
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 lookup the routing table and forwards 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 source
an 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 the entire host connected to the network whereas,
in multicast packet is delivered to intended recipients only.
 Multicast Message. Multicasting identifies logical groups of computers. A single
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 fileinthenameoffile2inthewritemode.
5. Openthetracefileinthenameoffile1inthewritemode.
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 no des including the delay time, band width
and dropping queue mechanism.
9. Give the position for the links between the nodes.
10. Set a tcp re no connection for source node.
11. Set the destination node using tcp sink.
12. Setup aftp 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:
setns[newSimulator]
#Definedifferentcolorsfordataflows(forNAM)
$nscolor 1Blue
$nscolor2Red#Open
theTracefile
setfile1[openout.trw]
$nstrace-all$file1
#Open the NAM trace
filesetfile2
[openout.namw]
$ns namtrace-all
$file2#Define a 'finish'
procedureprocfinish{}
{
globalnsfile1file2
$nsflush-
traceclose
$file1close$fil
e2
execnamout.nam&
exit3
}
#Nextlineshouldbecommentedouttohavethestaticrouting
$nsrtprotoDV#Cr
eatesixnodesset
n0 [$ns node]set
n1 [$ns node]set
n2 [$ns node]set
n4 [$ns node]set
n4 [$ns
node]setn5[$nsno
de]
#Createlinksbetweenthenodes
$nsduplex-link$n0$n1 0.3Mb10msDropTail
$nsduplex-link$n1$n2 0.3Mb10msDropTail
$nsduplex-link$n2$n3 0.3Mb10msDropTail
$nsduplex-link$n1$n4 0.3Mb10msDropTail
$nsduplex-link$n3$n5 0.5Mb10msDropTail
$nsduplex-link$n4$n5 0.5Mb10msDropTail

#Givenodeposition(forNAM)
$nsduplex-link-op$n0$n1orientright
$nsduplex-link-op$n1$n2orientright
$nsduplex-link-op$n2$n3orientup
$nsduplex-link-op$n1$n4orientup-left
$nsduplex-link-op$n3$n5orientleft-up
$nsduplex-link-op$n4$n5orientright-up

#Setupa TCPconnection
settcp[newAgent/TCP/Newreno]
$nsattach-agent$n0 $tcp
setsink[newAgent/TCPSink/DelAck]
$nsattach-agent$n5$sink
$nsconnect$tcp$sink
$tcpsetfid_1

#Setup a FTP over TCP


connectionsetftp
[newApplication/FTP]
$ftpattach-agent$tcp
$ftpsettype_FTP

$nsrtmodel-at1.0down$n1$n4
$nsrtmodel-at4.5up$n1$n4
$nsat0.1 "$ftp start"
$nsat6.0"finish"
$nsrun
(b) MULTICASTINGROUTINGPROTOCOL

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

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 animates or file in the name offile2 in the write mode.
5. Openthetracefileinthenameoffile1inthewritemode.
6. Set the multicast routing protocol to transfer the packets in network.
7. Create the multicast capable no of nodes.
8. Create the duplex-link between the node including the delay time, bandwidth and
dropping queue mechanism.
9. Give the position for the links between the nodes.
10. Set a udp connection for source node.
11. Set the destination node, port and random false for the source and destination files.
12. Setup a traffic generator CBR for the source and destination files.
13. Down the connection between any node at a particular time.
14. Create the receive agent for joining and leaving if the nodes in the group.
15. Define the finish procedure.
16. In the definition of the finish procedure are the global variables.
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:
#Create scheduler
#Create an event scheduler wit multicast turned
onsetns [new Simulator -multicaston]
#$nsmulticast#T
urnonTracing
settf[openoutput.trw]
$nstrace-all$tf
#TurnonnamTracingset
fd[openmcast.namw]
$nsnamtrace-
all$fd#Createnodes
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]setn7[$nsn
ode]

# Createlinks
$nsduplex-link$n0$n2 1.5Mb10msDropTail
$nsduplex-link$n1$n2 1.5Mb10msDropTail
$nsduplex-link$n2$n3 1.5Mb10msDropTail
$nsduplex-link$n3$n4 1.5Mb10msDropTail
$nsduplex-link$n3$n7 1.5Mb10msDropTail
$nsduplex-link$n4$n5 1.5Mb10msDropTail
$nsduplex-link$n4$n6 1.5Mb10msDropTail

#Routingprotocol:saydistancevector#P
rotocols: CtrMcast, DM, ST,
BSTsetmprotoDM
setmrthandle[$ns mrtproto$mproto{}]

# Allocate group
addressesset
group1[Nodeallocaddr]set
group2[Nodeallocaddr]

#UDPTransportagentforthetrafficsourcesetu
dp0[new Agent/UDP]
$nsattach-agent$n0$udp0
$udp0 setdst_addr_$group1
$udp0setdst_port_0
setcbr1[newApplication/Traffic/CBR]
$cbr1attach-agent$udp0

#Transportagentforthetrafficsourceset
udp1[newAgent/UDP]
$nsattach-agent$n1$udp1
$udp1 setdst_addr_$group2
$udp1setdst_port_0
setcbr2[newApplication/Traffic/CBR]
$cbr2attach-agent$udp1

#Createreceiver
set rcvr1[newAgent/Null]
$nsattach-agent$n5$rcvr1
$ns at 1.0 "$n5 join-group $rcvr1
$group1"setrcvr2[new Agent/Null]
$nsattach-agent$n6$rcvr2
$ns at 1.5 "$n6 join-group $rcvr2
$group1"setrcvr3[new Agent/Null]
$nsattach-agent$n7$rcvr3
$ns at 2.0 "$n7 join-group $rcvr3
$group1"setrcvr4[new Agent/Null]
$nsattach-agent$n5$rcvr1
$ns at 2.5 "$n5 join-group $rcvr4
$group2"setrcvr5[new Agent/Null]
$nsattach-agent$n6$rcvr2
$ns at 3.0 "$n6 join-group $rcvr5
$group2"setrcvr6[new Agent/Null]
$nsattach-agent$n7$rcvr3
$nsat3.5 "$n7 join-group$rcvr6 $group2"
$nsat4.0"$n5leave-group$rcvr1$group1"
$nsat4.5"$n6leave-group$rcvr2$group1"
$nsat5.0"$n7leave-group$rcvr3$group1"
$nsat5.5"$n5leave-group$rcvr4$group2"
$nsat6.0"$n6leave-group$rcvr5$group2"
$ns at 6.5 "$n7 leave-group $rcvr6

$group2"#Scheduleevents
$nsat0.5"$cbr1start"
$nsat9.5 "$cbr1stop"
$nsat0.5"$cbr2start"
$nsat9.5 "$cbr2stop"

#post-processing
$nsat10.0"finish"p
rocfinish{}
{

globalns tf
$ns flush-
traceclose $tf
execnammcast.nam&e
xit0
}

#Fornam
#Colorsforpacketsfromtwomcastgroups
$nscolor10red
$nscolor11 green
$nscolor30purple
$nscolor31 green

#Manual layout:orderofthelinkissignificant!
#$nsduplex-link-op $n0 $n1 orientright
#$nsduplex-link-op $n0 $n2orientright-up#$ns
duplex-link-op $n0 $n3 orient right-
down#Show queueonsimplexlinkn0->n1
#$nsduplex-link-op $n2 $n3 queuePos0.5

# Group0source
$udp0set fid_10
$n0colorred
$n0label"Source 1"

# Group1source
$udp1set fid_11
$n1color green
$n1label"Source 2"
$n5label"Receiver1"
$n5colorblue
$n6label"Receiver2"
$n6colorblue
$n7label"Receiver3"
$n7colorblue

#$n2add-
markm0red#$n2delete
-markm0"

#Animationrate
$nsset-animation-rate3.0ms
$nsrun
RESULT:
Thus the case study about the different routing algorithms to select the network path with
its optimum and economical during data transfer is done.
Ex.no :12 File Transfer using TCP Sockets

AIM:

To write a java program for file transfer using TCP Sockets.

Algorithm
Server

1. Import java packages and create class fileserver.


2. Create a new server socket and bind it to the port.
3. Accept the client connection
4. Get the filename and stored in to the Buffered Reader.
5. Create a new object class file and reline.
6. If file is exists then File Reader read the content until EOF is reached.
7. Stop the program.

Client

1. Import java packages and create class file server.


2. Create a new server socket and bind it to the port.
3. Now connection is established.
4. The object of a Buffer Reader class is used for storing data content which has been
retrieved from socket object.
5. The connection is closed.
6. Stop the program.
PROGRAM
FileServer:
importjava.io.BufferedInputStream;i
mportjava.io.File;
importjava.io.FileInputStream;
importjava.io.OutputStream;
importjava.net.InetAddress;
importjava.net.ServerSocket;
importjava.net.Socket
publicclassFileServer
{
publicstaticvoidmain(String[]args)throwsException
{
//InitializeSockets
ServerSocketssock=newServerSocket(5000);Socketso
cket=ssock.accept();
//TheInetAddressspecification
InetAddressIA=InetAddress.getByName("localhost");

//Specifythefile
File file = new File("e:\\
Bookmarks.html");FileInputStreamfis=newFileI
nputStream(file);
BufferedInputStreambis=newBufferedInputStream(fis);//
Getsocket'soutputstream
OutputStreamos=socket.getOutputStream();//
ReadFile Contents intocontentsarray
byte[] contents;
longfileLength=file.length();lo
ngcurrent= 0;
longstart
=System.nanoTime();while(curr
ent!=fileLength){
intsize=10000;
if(fileLength-
current>=size)current+=
size;
else{
size = (int)(fileLength -
current);current= fileLength;
}
contents=newbyte[size];
bis.read(contents,0,size);o
s.write(contents);
System.out.print("Sendingfile... "+(current*100)/fileLength+"%complete!");
}
os.flush();
//Filetransferdone.Closethesocket connection!
socket.close();
ssock.close();
System.out.println("Filesentsuccesfully!");
}}

FileClient:
importjava.io.BufferedOutputStream;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.net.InetAddress;
importjava.net.Socket;
publicclassFileClient{
publicstaticvoidmain(String[]args)throwsException{
//Initializesocket
Socket
socket=newSocket(InetAddress.getByName("localhost"),5000);byte[]contents=new
byte[10000];
//InitializetheFileOutputStreamtothe output file'sfullpath.FileOutputStream
fos=newFileOutputStream("e:\\Bookmarks1.html");
BufferedOutputStream bos = new
BufferedOutputStream(fos);InputStreamis=socket.getInputStre
am();
//
Noofbytesreadinoneread()call
intbytesRead= 0;
while((bytesRead=is.read(contents))!=-
1)bos.write(contents,0,bytesRead);
bos.flush();so
cket.close();
System.out.println("Filesavedsuccessfully!");
}
}
Output
server
E:\nwlab>java
FileServerSending file ... 9%
complete!Sending file ... 19%
complete!Sending file ... 28%
complete!Sending file ... 38%
complete!Sending file ... 47%
complete!Sending file ... 57%
complete!Sending file ... 66%
complete!Sending file ... 76%
complete!Sending file ... 86%
complete!Sending file ... 95%
complete!
Sendingfile...100%complete!
Filesentsuccessfully!

E:\nwlab>clientE:\
nwlab>java
FileClientFilesavedsucce
ssfully!

E:\nwlab>

RESULT:
Thus the java application program using TCP Sockets was developed and executed successfully

You might also like