Cs2307 Networks Lab Manual
Cs2307 Networks Lab Manual
Cs2307 Networks Lab Manual
1
SRINIVASAN ENGINEERING COLLEGE
COMPUTER SCIENCE AND ENGINEERING
ANNA UNIVERSITY CHENNAI
REGULATION 2009
III CSE (2010-2014)
CS2307
NETWORKS LAB
LAB MANUAL
PREPARED BY
S.NANDHINI DEVI, Assistant Professor
NILUTPAL BOSE, Assistant Professor
SEC CSE/V NETWORKS LAB MANUAL
2
PREFACE
This laboratory manual is prepared by the Department of Computer Science and
engineering for Networks Lab (CS2307). This lab manual can be used as instructional book for
students, staff and instructors to assist in performing and understanding the experiments. In the
first part of the manual, experiments as per syllabus are described and in the second part of the
manual, experiments that are beyond the syllabus but expected for university laboratory
examination are displayed. This manual will be available in electronic form from Colleges
official website, for the betterment of students.
SEC CSE/V NETWORKS LAB MANUAL
3
ACKNOWLEDGEMENT
With great pleasure and deep sense of gratitude, we take this opportunity to express
my hearty thanks and deep regards to the support offered by the chairman Shri.
A.Srinivasan.
We also take this opportunity to express a deep sense of gratitude to our Principal
Dr.B.Karthikeyan, for his valuable information and guidance, which helped me in
completing this task through various stages.
We extend our hearty thanks to our head of the department Asst.Prof.Jayanthi.S
M.E, for her constant encouragement and constructive comments.
Finally the valuable comments from fellow faculty and assistance provided by the
department are highly acknowledged. We would like to thank everyone who helped us at
various stages in completing this work.
Last but not least we express our heartfelt thanks to Lord Almighty for being there
when we needed him most always.
SEC CSE/V NETWORKS LAB MANUAL
4
Chapter no Topic Page no
I
Introduction to the language
Main features
Advantages
Limitations
Application
5
II Syllabus 11
III System Requirements 12
IV About Networks Lab
Aim
Description about each experiment
Learning Objectives
General procedure to execute programs
13
V Exp No
Title
1
i) Programs using TCP Sockets (like date and time
ii) Programs using TCP Sockets (echo server and client)
16
20
2 Programs using UDP Sockets
25
3 Programs using Raw sockets
30
4 Programs using RPC
36
5 Simulation of sliding window protocols
41
6 Simulation of Routing Protocol
46
7
Implementing MAC protocols
50
8 Implementing Routing Protocols(OSPF)
53
9 Study of TCP/UDP Performance
57
VI
Experiments beyond the syllabus
61
SEC CSE/V NETWORKS LAB MANUAL
5
CHAPTER 1
INTRODUCTION OF THE LANGUAGE (CORRESPONDING VERSION)
TURBO C
C is a general-purpose programming language initially developed by Dennis
Ritchie between 1969 and 1973 at AT&T Bell Labs.
The initial development of C occurred at AT&T Bell Labs between 1969 and 1973;
according to Ritchie, the most creative period occurred in 1972. It was named "C" because
its features were derived from an earlier language called "B", which according to Ken
Thompson was a stripped-down version of the BCPL programming language.
The origin of C is closely tied to the development of the Unix operating system,
originally implemented in assembly language on a PDP-7 by Ritchie and Thompson,
incorporating several ideas from colleagues. Eventually they decided to port the operating
system to a PDP-11. B's inability to take advantage of some of the PDP-11's features,
notably byte addressability, led to the development of an early version of C.
C is one of the most widely used programming languages of all time, and there are
very few computer architectures for which a C compiler does not exist.
C allows programmers to manipulate the main elementsbytes, bits, and
addresses that influence the way a computer functions.
Programs written in C are efficient and fast. This is due to its variety of data types
and powerful operators. It is many times faster than BASIC.
Another important feature of C is its ability to extend itself. A program is
basically a collection of functions, which are supported by the C library
Importance/Advantages of programming in C:
Easy to understand.
Freedom of using different type of data.
SEC CSE/V NETWORKS LAB MANUAL
6
Short listed words could be use.
Efficient and fast programming.
It can be used as mid-level language.
Any type of software and operating system be developed with the help of C
language.
LIMITATIONS
Weak text processing capabilities - C's string library is extremely primitive (it
doesn't even define an actual string type), and text processing is labor-intensive and
error-prone.
Security and safety issues: several library functions (gets() being the most
notorious) provide easy exploits for malware, and anything involving pointers is
going to be unsafe (it's hard to guard against being passed an invalid pointer);
Weak memory management capabilities - Like text processing, managing
memory in C is labor-intensive and error-prone
No built-in collections library - C doesn't provide ready made collections (lists, ,
stacks, etc.), meaning you have to roll your own
No built-in support for networking, sound, graphics, etc. - C is a product of the
early 1970s and it shows; byte streams are about the highest level of abstraction
you're going to find in the C library.
SEC CSE/V NETWORKS LAB MANUAL
7
APPLICATIONS
C language is used for creating computer applications and also used a lot in writing
embedded software/firmware for various electronics, industrial and communications
products which use micro-controllers.
It is also used in developing verification software, test code, simulators etc. for
various applications and hardware products.
C has been used successfully for every type of programming problem imaginable
from operating systems to spreadsheets to expert systems
C was initially used for system development work, in particular the programs that
make-up the operating system.
C has been used as a general-purpose language because of its popularity with pro
JAVA
Java is an Object Oriented programming language developed by Sun Microsystems
in 1991.Initially it was known as Oak but latter it renamed to java. Java was developed by
taking the best points from other programming languages, primarily C and C++. Java is
such a great language and platform for any kind of application. It is open, fast, powerful,
runs on any platform, and there are more jobs for Java than any other programming
language.Java is a well known technology which allows you for software designed and
written only once for an "virtual machine" to run on a different computers, supports
various Operating System like Windows PCs, Macintoshes, and Unix computers.Error
prone tasks such as pointers and memory management have either been eliminated or are
handled by the Java environment automatically rather than by the programmer.
Advantages of JAVA
JAVA offers a number of advantages to developers.
Java is simple: Java was designed to be easy to use and is therefore easy to write,
compile, debug, and learn than other programming languages. The reason that why Java is
much simpler than C++
SEC CSE/V NETWORKS LAB MANUAL
8
Java is object-oriented: Java is object-oriented because programming in Java is
centered on creating objects, manipulating objects, and making objects work together.
This allows you to create modular programs and reusable code.
Java is platform-independent: One of the most significant advantages of Java is its
ability to move easily from one computer system to another.
Java is distributed: Distributed computing involves several computers on a
network working together. Java is designed to make distributed computing easy
with the networking capability that is inherently integrated into it. Writing network
programs in Java is like sending and receiving data to and from a file.
Java is interpreted: An interpreter is needed in order to run Java programs. The
programs are compiled into Java Virtual Machine code called bytecode. The bytecode is
machine independent and is able to run on any machine that has a Java interpreter.
Java is secure: Java is one of the first programming languages to consider security as
part of its design. The Java language, compiler, interpreter, and runtime environment
were each developed with security in mind.
Current Limitations and Disadvantages of Java
These exist mostly because the language is still evolving.
1. Slow
o Internet as a whole
Potential huge show-stopper problem.
Bandwidth is a limited resource that is easily squandered.
Minimal incentive for people to conserve.
Potential demand is unbounded, potential supply is bounded.
SEC CSE/V NETWORKS LAB MANUAL
9
Solutions:
Write applications instead of applets (but then
you lose some advantages)
Cache your applets (only partial solution).
Java compiler:
Not yet well optimized.
Takes more time to compile a large program than a good
C++ compiler.
2. Environment limitations
Currently lacks:
Browser
Interactive source-level debugger
User interface builder
3. Applet limitations imposed due to security
Cannot access local data
Can only download data from the site where the applet is located
Cannot make system calls
Solution: Use applications
4. Programming language limitations
No `Templates' yet.
Limits ability to create really good data structures
No `Function pointers' or `blocks'
These would allow greater abstraction and more flexible data-
structure design
Available in both C++ and Smalltalk
Basic classes in class library are lacking important features
SEC CSE/V NETWORKS LAB MANUAL
10
The class library was created to quickly and has now been
widely adopted, making it hard to change.
This is also a problem with other languages
We can expect the current widespread standardization to
fragment as vendors introduce competing classes to fill the gaps
5. Platform limitations
Full environment available only for:
Windows 95/NT
Macintosh
Sun Solaris
Other platforms must wait for 3rd party support
Application Java programming Language :
Since Java has inbuilt networking features so it is widely used for developing
network related programs and softwares. Socket Programming using JAVA is very
simple and efficient and simple as compared to c.
It is widely used for creating web applications and it can also generate static
HTML content like PHP and JavaScript so it is used in website designing too.
In application software development Java is widely used because it is a fully Object
Oriented programming language.
Creating Graphical User Interface(GUI) in Java is very simple and efficient as
compared to C and C++.So it is also used in creating GUI for applications.
SEC CSE/V NETWORKS LAB MANUAL
11
CHAPTER 2
SYLLABUS
CS2307 NETWORKS LABORATORY
LIST OF EXPERIMENTS
1. Programs using TCP Sockets (like date and time server & client, echo server &
Client, etc...)
2. Programs using UDP Sockets (like simple DNS)
3. Programs using raw sockets (like packet capturing and filtering)
4. Programs using RPC
5. Simulation of sliding window protocols
6. Experiments using simulators (like OPNET)
7. Performance comparison of MAC protocols
8. Performance comparison of Routing protocols
9. Study of TCP/UDP performance
SEC CSE/V NETWORKS LAB MANUAL
12
CHAPTER 3
SYSTEM REQUIREMENTS
1 HARDWARE REQUIREMENTS:
Intel Pentium 915 GV
80GB SATA II
512MB DDR
2 SOFTWARE REQUIREMENTS:
C
JAVA
SEC CSE/V NETWORKS LAB MANUAL
13
CHAPTER 4
ABOUT NETWORKS LABORATORY:
1 AIM
The aim of the Networks laboratory is to give students a good understanding of
basic concepts of computer networks and the need of developing networks based
applications.
2 DESCRIPTIONS ABOUT EACH EXPERIMENT
EXPERIMENT NO 1: PROGRAMS USING TCP SOCKETS ( LIKE DATE-TIME
SERVER&CLIENT , ECHO SERVER CLIENT)
Every time when a client connects to the server, servers date/time will be returned
to the client for synchronization.
EXPERIMENT NO 2: PROGRAMS USING UDP SOCKETS (LIKE SIMPLE DNS)
The domain name requests by the client are resolved into their respective logical
address using lookup method.
EXPERIMENT NO 3: PROGRAMS USING RAW SOCKETS (LIKE PACKET CAPTURING AND
FILTERING)
Thus the above programs using raw sockets TCP \IP (like packet capturing and
filtering)
EXPERIMENT NO 4: . PROGRAMS USING RPC
To implement fibonacci series on a remote host and generate terms onto a client.
EXPERIMENT NO 5: SIMULATION OF SLIDING WINDOW PROTOCOLS
A sliding window protocol is a feature of packet-based data transmission
protocol. Sliding window protocols are used where reliable in-order delivery of
packets is required, such as in the Data link layer (OSI model) as well as in the
transmission control protocol (TCP).
SEC CSE/V NETWORKS LAB MANUAL
14
EXPERIMENT NO 6: EXPERIMENTS USING SIMULATORS (LIKE OPNET)
To get the MAC or Physical address of the system using Address Resolution
Protocol.
EXPERIMENT NO 7: PERFORMANCE COMPARISION OF MAC PROTOCOLS
Medium Access Control Protocol determines a particular way a medium is
accessed for communication .It comes under the data link layer of 7layer OSI model for
Network communication. It provides a Mechanism to access a particular terminal or a
network example a LAN(local area network) or a MAN(metropolitan area network).
EXPERIMENT NO 8: PERFORMANCE COMPARISION OF ROUTING PROTOCOLS
A routing protocol specifies how routers communicate with each other,
disseminating information that enables them to select routes between any two nodes on
computer networks. Routing algorithms determine the specific choice of route
EXPERIMENT NO 9: STUDY OF TCP/UDP PERFORMANCE
The Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP)
are both IP transport-layer protocols. UDP is a lightweight protocol that allows applications
to make direct use of the unreliable datagram service provided by the underlying IP service.
UDP is commonly used to support applications that use simple query/response transactions,
or applications that support real-time communications. TCP provides a reliable data-transfer
service, and is used for both bulk data transfer and interactive data applications.
3.LEARNING OBJECTIVES:
The purpose of this course is to be able to explain, configure, verify, and
troubleshoot complex computer networks at an introductory level. At the successful
completion of this class a student will be able to say: I can explain computer networking
concepts to both technical peers and non-technical management. I can configure network
routers and switches so that both LAN and WAN traffic successfully traverses the network.
SEC CSE/V NETWORKS LAB MANUAL
15
I can verify that a computer network has been properly configured. I
can troubleshoot network problems. I can successfully implement solutions. I
can discern true statements from false statements as pertains to computer networking as
verified by passing industry standard examinations.
4 GENERAL PROCEDURE FOR EXECUTING PROGRAM
C Program
First of all the source code is get compiled and the object code is returned i.e.binary
code(machine language).Then the linker is called Linker, a computer program that takes
one or more objects generated by a compiler and combines them into a single executable
program. Now when the program is executed then the .exe file is first loaded into the
memory and then executed by the processor.
In short the steps are :
1.Compilation
2.Linking
3.Loading
4.Execution
JAVA
First of all the source code gets compiled and the class file is genearted i.e.byte
code(machine language).Then the byte code generated using java compiler and combines
them into a single executable program. Now when the program is executed then the .java
file is first loaded into the memory and then executed by the processor.
In short the steps are :
1.Compilation
2.Byte code generation
3.Loading
4.Execution
SEC CSE/V NETWORKS LAB MANUAL
16
CHAPTER 5
To implement date and time server and client in java using TCP sockets.
Objective
TCP Server gets the system date and time and opens the server socket to read
the client details. Client send its address to the server. Then client receives the date and
time from server to display.
How it is being achieved?
TCP socket server client connection is opened for communication.After the date
time is displayed the server client connection is closed with its respective streams to be
closed.
Syntax & keywords
To display date & time:
Date d = new Date();
ps.println(d);
dis = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
inet = dis.readLine();
HOW TO EXECUTE THE SOURCE CODE
Create a java program and save it using the class name as sample.java file.
Then compile sample.java using the command javac sample.java
Run the java program to get the output using the command java sample
EX NO: 1 i)
IMPLEMENTATION OF TCP SOCKETS (LIKE DATE & TIME SERVER-CLIENT)
DESCRIPTION ABOUT THE EXPERIMENT
SEC CSE/V NETWORKS LAB MANUAL
17
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler JAVA
EXPECTED OUTPUT AND ITS FORM
This program implements system date and time to be obtained as input by server to
send it to client to display as output.
ADVANTAGES
Used to perform real time applications (Display current date)
ALGORITHM
Server
Client
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Send servers date and time to the client.
4. Read clients ip address sent by the client.
5. Display the client details.
6. Repeat steps 2-5 until the server is terminated.
7. Close all streams.
8. Close the server socket.
9. Stop.
1. Create a client socket and connect it to the servers port number.
2. Retrieve its own ip address using built-in function.
3. Send its address to the server.
4. Display the date & time sent by the server.
5. Close the input and output streams.
6. Close the client socket.
7. Stop.
SEC CSE/V NETWORKS LAB MANUAL
18
PROGRAM:
//TCP Date Server--tcpdateserver.java
import java.net.*;
import java.io.*;
import java.util.*;
class tcpdateserver
{
public static void main(String arg[])
{
ServerSocket ss = null;
Socket cs;
PrintStream ps;
BufferedReader dis;
String inet;
try
{
ss = new ServerSocket(4444);
System.out.println("Press Ctrl+C to quit");
while(true)
{
cs = ss.accept();
ps = new PrintStream(cs.getOutputStream());
Date d = new Date();
ps.println(d);
dis = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
inet = dis.readLine();
System.out.println("Client System/IP address is :"+ inet);
ps.close();
dis.close();
}
}
catch(IOException e)
{
System.out.println("The exception is :" + e);
}
}
}
// TCP Date Client--tcpdateclient.java
import java.net.*;
import java.io.*;
class tcpdateclient
{
public static void main (String args[])
SEC CSE/V NETWORKS LAB MANUAL
19
{
Socket soc;
BufferedReader dis;
String sdate;
PrintStream ps;
try
{
InetAddress ia = InetAddress.getLocalHost();
if (args.length == 0)
soc = new Socket(InetAddress.getLocalHost(),4444);
else
soc = new Socket(InetAddress.getByName(args[0]),
4444);
dis = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
sdate=dis.readLine();
System.out.println("The date/time on server is : " +sdate);
ps = new PrintStream(soc.getOutputStream());
ps.println(ia);
ps.close();
}
catch(IOException e)
{
System.out.println("THE EXCEPTION is :" + e);
}
}
}
OUTPUT
Server:
$ javac tcpdateserver.java
$ java tcpdateserver
Press Ctrl+C to quit
Client System/IP address is : localhost.localdomain/127.0.0.1
Client System/IP address is : localhost.localdomain/127.0.0.1
Client:
$ javac tcpdateclient.java
$ java tcpdateclient
The date/time on server is: Wed Jul 06 07:12:03 GMT 2011
RESULT
Thus every time a client connects to the server, servers date/time will be returned
to the client for synchronization.
SEC CSE/V NETWORKS LAB MANUAL
20
EX NO: 1ii)
IMPLEMENTATION OF TCP/IP ECHO
DESCRIPTION ABOUT THE EXPERIMENT
To implement echo server and client in java using TCP sockets.
Objective
TCP Server gets the message and opens the server socket to read the client
details. Client send its address to the server. Then client receives the message from
server to display.
How it is being achieved?
TCP socket server client connection is opened for communication .After the
message is displayed the server client connection is closed with its respective streams to
be closed.
Syntax & keywords
To display bye message:
if (Usrmsg==null || Usrmsg.equals("bye"))
{
toServer.println("bye");
break;
}
HOW TO EXECUTE THE SOURCE CODE
Create a java program and save it using the class name as sample.java file.
Then compile sample.java using the command javac sample.java
Run the java program to get the output using the command java sample
SEC CSE/V NETWORKS LAB MANUAL
21
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler JAVA
EXPECTED OUTPUT AND ITS FORM
This program implements echo message to be obtained as input by server to send it
to client to display as output.
ALGORITHM
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Read the data from client.
4. Echo the data back to the client.
5. Repeat steps 4-5 until bye or null is read.
6. Close all streams.
7. Close the server socket.
8. Stop.
Client
1. Create a client socket and connect it to the servers port number.
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send user data to the server.
5. Display the data echoed by the server.
6. Repeat steps 2-4.
7. Close the input and output streams.
8. Close the client socket.
9. Stop.
SEC CSE/V NETWORKS LAB MANUAL
22
PROGRAM:
// TCP Echo Server--tcpechoserver.java
import java.net.*;
import java.io.*;
public class tcpechoserver
{
public static void main(String[] arg) throws IOException
{
ServerSocket sock = null;
BufferedReader fromClient = null;
OutputStreamWriter toClient = null;
Socket client = null;
try
{
sock = new ServerSocket(4000);
System.out.println("Server Ready");
client = sock.accept();
System.out.println("Client Connected");
fromClient = new BufferedReader(new
InputStreamReader(client.getInputStream()));
toClient = new
OutputStreamWriter(client.getOutputStream());
String line;
while (true)
{
line = fromClient.readLine();
if ( (line == null) || line.equals("bye"))
break;
System.out.println ("Client [ " + line + " ]");
toClient.write("Server [ "+ line +" ]\n");
toClient.flush();
}
fromClient.close();
toClient.close();
client.close();
sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{
System.err.println(ioe);
}
}
}
SEC CSE/V NETWORKS LAB MANUAL
23
//TCP Echo Client--tcpechoclient.java
import java.net.*;
import java.io.*;
public class tcpechoclient
{
public static void main(String[] args) throws IOException
{
BufferedReader fromServer = null, fromUser = null;
PrintWriter toServer = null;
Socket sock = null;
try
{
if (args.length == 0)
sock = new Socket(InetAddress.getLocalHost(),4000);
else
sock = new Socket(InetAddress.getByName(args[0]),4000);
fromServer = new BufferedReader(new
InputStreamReader(sock.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
toServer = new PrintWriter(sock.getOutputStream(),
true
String Usrmsg, Srvmsg;
System.out.println("Type \"bye\" to quit");
while (true)
{
System.out.print("Enter msg to server : ");
Usrmsg = fromUser.readLine();
if (Usrmsg==null || Usrmsg.equals("bye"))
{
toServer.println("bye");
break;
} else
toServer.println(Usrmsg);
Srvmsg = fromServer.readLine();
System.out.println(Srvmsg);
} fromUser.close();
fromServer.close();
toServer.close();
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}
SEC CSE/V NETWORKS LAB MANUAL
24
OUTPUT
Server:
$ javac tcpechoserver.java
$ java tcpechoserver
Server Ready
Client Connected
Client [ hello ]
Client [ how are you ]
Client [ i am fine ]
Client [ ok ]
Client Disconnected
Client :$ javac tcpechoclient.java
$ java tcpechoclient
Type "bye" to quit
Enter msg to server : hello
Server [ hello ]
Enter msg to server : how are you
Server [ how are you ]
Enter msg to server : i am fine
Server [ i am fine ]
Enter msg to server : ok
Server [ ok ]
Enter msg to server : bye
RESULT
Thus data from client to server is echoed back to the client to check reliability/noise
level of the channel.
VIVA QUESTIONS
1.What is TCP socket ?
In TCP/IP and UDP networks, a port is an endpoint to a logical connection and the
way a client program specifies a specific server program on a computer in a network. This
list of well-known port numbers specifies the port used by the server process as its contact
port.
2. What is ECHO command?
ECHO command is used to display the message send from server to client.
SEC CSE/V NETWORKS LAB MANUAL
25
EX.NO: 2
PROGRAM USING UDP SOCKETS ( DOMAIN NAME SYSTEM)
DESCRIPTION ABOUT THE EXPERIMENT
To implement DNS server and client in java using UDP sockets.
Objective
UDP Server gets the domain name and opens the server socket to read the client
details. Client send its address to the server. Then client receives the domain name and its
address from server to display.
How it is being achieved?
UDP socket server client connection is opened for communication .After the unique
host name is identified to be displayed .Then server client connection is closed along
with its respective streams to be closed.
Syntax & keywords
To get IP address of host:
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
HOW TO EXECUTE THE SOURCE CODE
Create a java program and save it using the class name as sample.java file.
Then compile sample.java using the command javac sample.java
Run the java program to get the output using the command java sample
SEC CSE/V NETWORKS LAB MANUAL
26
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler JAVA
EXPECTED OUTPUT AND ITS FORM
This program implements DNS to get host name as input by server and identifies IP
address of host is sent to be display as output by the client.
ALGORITHM
Server
1. Create an array of hosts and its ip address in another array
2. Create a datagram socket and bind it to a port
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Create a datagram packet and send ip address to client
8. Repeat steps 3-7 to resolve further requests from clients
9.Close the server socket
10. Stop
Client
1. Create a datagram socket
2. Get domain name from user
3. Create a datagram packet and send domain name to the server
4. Create a datagram packet to receive server message
5. Read server's response
6. If ip address then display it else display "Domain does not exist"
7. Close the client socket
8. Stop
SEC CSE/V NETWORKS LAB MANUAL
27
PROGRAM
// UDP DNS Server -- udpdnsserver.java
import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str))
return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com",
"cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19",
"80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021]; byte[]
receivedata = new byte[1021]; DatagramPacket
recvpack = new DatagramPacket(receivedata,
receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
SEC CSE/V NETWORKS LAB MANUAL
28
serversocket.close();
}
}
}
//UDP DNS Client -- udpdnsclient.java
import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,
senddata.length, ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new DatagramPacket(receivedata,
receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}
}
OUTPUT
Server
$ javac udpdnsserver.java
$ java udpdnsserver Press Ctrl + C
to Quit Request for host yahoo.com
Request for host cricinfo.com
Request for host youtube.com
SEC CSE/V NETWORKS LAB MANUAL
29
Client
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
$ java udpdnsclient
Enter the hostname : cricinfo.com
IP Address: 80.168.92.140
$ java udpdnsclient
Enter the hostname : youtube.com
IP Address: Host Not Found
RESULT
Thus domain name requests by the client are resolved into their respective logical
address using lookup method.
VIVA QUESTIONS
1. What is UDP socket ?
UDP is a connectionless protocol and the socket is created for client and
server to transfer the data. Socket connection is achieved using the port number
2. What is DNS?
DNS stands for domain name system. unique name of the host is identified
with its IP address through server client communication.
SEC CSE/V NETWORKS LAB MANUAL
30
EX NO: 3
PROGRAM USING RAW SOCKETS (PACKET CAPTURING AND FILTERING)
DESCRIPTION ABOUT THE EXPERIMENT
To implement raw sockets like packet capturing and filtering using java .
Objective
Raw socket is created to define the transmission of packet. Packet is captured
for checking error. Error containing packets are filtered during transmission.
How it is being achieved?
Raw socket using TCP/IP protocol is created . Packet length is defined along with
TCP header attached. Packets with error are checked using CRC mechanism and filtered.
Syntax & keywords
Redundancy Check, CRC
unsigned short csum(unsigned short *buf, int len)
{
unsigned long sum;
for(sum=0; len>0; len--)
sum += *buf++;
sum = (sum >> 16) + (sum &0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
HOW TO EXECUTE THE SOURCE CODE
SEC CSE/V NETWORKS LAB MANUAL
31
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler C
EXPECTED OUTPUT AND ITS FORM
This program implements raw socket to define packets with length as input . Then
packet is captured and filtered to display the packets without error as output.
ALGORITHM
1. Start the program and to include the necessary header files.
2. To define the packet length.
3. To declare the IP header structure using TCP header.
4. Using simple checksum process to check the process.
5. Using TCP \IP communication protocol to execute the program.
6. And using TCP\IP communication to enter the Source IP and port number and
Target IP address and port number.
7. The Raw socket () is created and accept the Socket ( ) and Send to ( ), ACK
8. Stop the program
PROGRAM:
//---cat rawtcp.c---
// Run as root or SUID 0, just datagram no data/payload
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
// Packet length
#define PCKT_LEN 8192
// May create separate header file (.h) for all
// headers' structures
// IP header's structure
struct ipheader {
SEC CSE/V NETWORKS LAB MANUAL
32
unsigned char iph_ihl:5, /* Little-endian */
iph_ver:4;
unsigned char iph_tos;
unsigned short int iph_len;
unsigned short int iph_ident;
unsigned char iph_flags;
unsigned short int iph_offset;
unsigned char iph_ttl;
unsigned char iph_protocol;
unsigned short int iph_chksum;
unsigned int iph_sourceip;
unsigned int iph_destip;
};
/* Structure of a TCP header */
struct tcpheader {
unsigned short int tcph_srcport;
unsigned short int tcph_destport;
unsigned int tcph_seqnum;
unsigned int tcph_acknum;
unsigned char tcph_reserved:4, tcph_offset:4;
// unsigned char tcph_flags;
unsigned int
tcp_res1:4, /*little-endian*/
tcph_hlen:4, /*length of tcp header in 32-bit
words*/
tcph_fin:1, /*Finish flag "fin"*/
tcph_syn:1, /*Synchronize sequence numbers to
start a connection*/
tcph_rst:1, /*Reset flag */
tcph_psh:1, /*Push, sends data to the
application*/
tcph_ack:1, /*acknowledge*/
tcph_urg:1, /*urgent pointer*/
tcph_res2:2;
unsigned short int tcph_win;
unsigned short int tcph_chksum;
unsigned short int tcph_urgptr;
};
// Simple checksum function, may use others such as Cyclic
Redundancy Check, CRC
unsigned short csum(unsigned short *buf, int len)
{
unsigned long sum;
for(sum=0; len>0; len--)
sum += *buf++;
sum = (sum >> 16) + (sum &0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
SEC CSE/V NETWORKS LAB MANUAL
33
}
int main(int argc, char *argv[])
{
int sd;
// No data, just datagram char
buffer[PCKT_LEN];
// The size of the headers
struct ipheader *ip = (struct ipheader *) buffer;
struct tcpheader *tcp = (struct tcpheader *) (buffer +
sizeof(struct ipheader)); struct
sockaddr_in sin, din; int one =
1;
const int *val = &one;
memset(buffer, 0, PCKT_LEN);
if(argc != 5)
{
printf("- Invalid parameters!!!\n");
printf("- Usage: %s <source hostname/IP> <source port>
<target hostname/IP> <target port>\n", argv[0]);
exit(-1);
}
sd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);
if(sd < 0)
{
perror("socket() error");
exit(-1);
}
else
printf("socket()-SOCK_RAW and tcp protocol is OK.\n");
// The source is redundant, may be used later if needed
// Address family
sin.sin_family = AF_INET;
din.sin_family = AF_INET;
// Source port, can be any, modify as needed
sin.sin_port = htons(atoi(argv[2])); din.sin_port
= htons(atoi(argv[4]));
// Source IP, can be any, modify as needed
sin.sin_addr.s_addr = inet_addr(argv[1]);
din.sin_addr.s_addr = inet_addr(argv[3]);
// IP structure
ip->iph_ihl = 5; ip-
>iph_ver = 4; ip-
>iph_tos = 16;
ip->iph_len = sizeof(struct ipheader) + sizeof(struct
tcpheader);
ip->iph_ident = htons(54321);
ip->iph_offset = 0;
SEC CSE/V NETWORKS LAB MANUAL
34
ip->iph_ttl = 64;
ip->iph_protocol = 6; // TCP
ip->iph_chksum = 0; // Done by kernel
// Source IP, modify as needed, spoofed, we accept through
command line argument
ip->iph_sourceip = inet_addr(argv[1]);
// Destination IP, modify as needed, but here we accept
through command line argument
ip->iph_destip = inet_addr(argv[3]);
// The TCP structure. The source port, spoofed, we accept
through the command line
tcp->tcph_srcport = htons(atoi(argv[2]));
// The destination port, we accept through command line
tcp->tcph_destport = htons(atoi(argv[4]));
tcp->tcph_seqnum = htonl(1);
tcp->tcph_acknum = 0;
tcp->tcph_offset = 5; tcp-
>tcph_syn = 1;
tcp->tcph_ack = 0;
tcp->tcph_win = htons(32767);
tcp->tcph_chksum = 0; // Done by kernel
tcp->tcph_urgptr = 0;
// IP checksum calculation
ip->iph_chksum = csum((unsigned short *) buffer,
(sizeof(struct ipheader) + sizeof(struct tcpheader)));
// Inform the kernel do not fill up the headers' structure, we
fabricated our own
if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one))
< 0)
{
perror("setsockopt() error");
exit(-1);
}
else
printf("setsockopt() is OK\n");
printf("Using:::::Source IP: %s port: %u, Target IP:
%s port: %u.\n", argv[1], atoi(argv[2]), argv[3],
atoi(argv[4]));
// sendto() loop, send every 2 second for 50
counts unsigned int count;
for(count = 0; count < 20; count++)
{
if(sendto(sd, buffer, ip->iph_len, 0, (struct sockaddr
*)&sin, sizeof(sin)) < 0)
// Verify
{
perror("sendto() error");
SEC CSE/V NETWORKS LAB MANUAL
35
exit(-1);
}
else
printf("Count #%u - sendto() is OK\n", count);
sleep(2);
}
close(s
d);
return
0;
}
OUTPUT:
Setsockopt() is OK
Using Source IP : 172.17.1.72
Port : 3001
Target IP: 172.17.1.76
Port : 5001
RESULT:
Thus the above programs using raw sockets TCP \IP (like packet capturing and
filtering) was executed and successfully
VIVA QUESTIONS
1. What is raw socket?
Raw socket is similar to the TCP or UDP socket and raw socket is used to capture the
packet of data and filter packet with error.
2. What is CRC?
CRC stands for cyclic redundancy check .CRC is used to check the bit with error
present along with the original data with some calculation procedure.
SEC CSE/V NETWORKS LAB MANUAL
36
EX NO: 4
PROGRAM USING RPC(Remote Procedure Call)
DESCRIPTION ABOUT THE EXPERIMENT
To implement factorial on a remote host and obtain its value from a client.
Objective
Factorial function is defined to return the necessary value. Remote procedure is
invoked to execute the factorial of given number.
How it is being achieved?
For RPC the following steps like interface with declaration of functions,
implementation contains the definition of declaration of functions, server-client procedures
for execution.
Syntax & keywords
Remote method interface declarations:
import java.rmi.*;
public interface FactIntf extends Remote
{
long factorial(int n)throws RemoteException;
}
HOW TO EXECUTE THE SOURCE CODE
Procedure
1. Compile the four java files (Interface, Implementation, Server and Client)
2. Generate stub by compiling the implementation file using RMI compiler
3. Distribute the class files of Client, Interface and Stub to the client machines
4. Start the RMI registry on the server
5. Start the server
6. Call procedures that exist on the remote host from client machine.
SEC CSE/V NETWORKS LAB MANUAL
37
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler JAVA
EXPECTED OUTPUT AND ITS FORM
This program implements RPC to enter an integer as input to input by server and
to get factorial of that integer as output.
ALGORITHM
Interface
Declare server's remote interface for Factorial by extending Remote interface
Implementation
Define the procedure for factorial (n! = n (n-1) 1) that extends
UnicastRemoteObject.
Server
Client
1. Create a interface object
2. Register the object with the RMI registry on the server machine using rebind
method
1. Obtain number from the user
2. Lookup for the Factorial service on the remote server
3. Call the remote factorial method
4. Display factorial value.
SEC CSE/V NETWORKS LAB MANUAL
38
PROGRAM
// remote method interface--FactIntf.java
import java.rmi.*;
public interface FactIntf extends Remote
{
long factorial(int n)throws RemoteException;
}
//Remote behaviour implementation--FactImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class FactImpl extends UnicastRemoteObject implements
FactIntf
{
public FactImpl() throws RemoteException { }
public long factorial(int n)throws RemoteException
{
long f = 1;
for(int i=n; i>0; i--)
f *= i;
return f;
}
}
//Server that registers the service--FactServer.java
import java.rmi.*;
public class FactServer
{
public static void main(String arg[])
{
try
{
FactIntf Fa = new FactImpl();
Naming.rebind("FactService", Fa);
}
catch(Exception e)
{ System.out.println(e.getMessage());
}
}
}
// Client that invokes remote host methods--FactClient.java
import java.rmi.*;
import java.net.*;
SEC CSE/V NETWORKS LAB MANUAL
39
public class FactClient
{
public static void main(String args[])
{
try
{
FactIntf Fa = (FactIntf) Naming.lookup("rmi://" +
args[0] + "/FactService");
if (args.length != 2)
{
System.out.println("Usage: java FactClient
<remoteip> <number>");
System.exit(-1);
}
int n = Integer.parseInt(args[1]); long factval =
Fa.factorial(n); System.out.print("\n" + n + " Factorial
value is " + factval);
}
catch(Exception e)
{ System.out.println(e.getMessage());
}
}
}
OUTPUT
Server
C:\>javac FactIntf.java
C:\>javac FactImpl.java
C:\>javac FactServer.java
C:\>javac FactClient.java
C:\>rmic FactImpl
C:\>start rmiregistry
C:\>java FactServer
Client
C:\>java FactClient 172.16.6.45 10
10 Factorial value is 3628800
C:\>java FactClient 172.16.6.45 0
0 Factorial value is 1
SEC CSE/V NETWORKS LAB MANUAL
40
RESULT
Thus remote procedure call to determine factorial value is executed using Java RMI.
VIVA QUESTIONS
1. What is RPC?
A remote procedure call (RPC) is an IPC that allows a computer program to
cause a subroutine or procedure to execute in another address space (commonly on
another computer on a shared network) without the programmer explicitly coding the
details for this remote interaction.
2. What is interface?
An interface is the point of interaction with software or computer hardware, or
with peripheral devices such as a computer monitor or a keyboard computing. Some
computer interfaces such as a touch screen can send and receive data, while others such
as a mouse or microphone, can only send data.
SEC CSE/V NETWORKS LAB MANUAL
41
EX NO: 5
SIMULATION OF SLIDING WINDOW PROTOCOL
DESCRIPTION ABOUT THE EXPERIMENT
To write a C program to perform sliding window.
Objective
A sliding window frame of data is sent from server to client. If that frame is received
correctly at the client then acknowledgement signal is sent to server. Otherwise negative
acknowledgement is sent.
How it is being achieved?
Frame size for the sliding window is provided by the user. Then the frame of data is
sent with ACK signal or NACK signal.
Syntax & keywords
To receive the frames :
if((msgrcv(msgid,&buf,sizeof(buf),0,1))==-1)
{
printf("\n ERROR IN MSGRCV");
exit(0);
}
printf("\n RECEIVED FRAMES ARE:%c",buf.mtext[i]);
}
HOW TO EXECUTE THE SOURCE CODE
SEC CSE/V NETWORKS LAB MANUAL
42
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler C
EXPECTED OUTPUT AND ITS FORM
This program implements sliding window protocol to get frame size as input and
display the frame of data as output.
ALGORITHM
1. Start the program.
2. Get the frame size from the user.
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal to client.
6. Stop the program.
PROGRAM:
// SLIDING WINDOW PROTOCOL
Client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mymsgbuf
{
long mtype;
char mtext[25];
};
SEC CSE/V NETWORKS LAB MANUAL
43
FILE *fp;
int main()
{
struct mymsgbuf buf;
int msgid;
int i=0,s;
int count=0,frmsz;
int a[100];
char d;
if((msgid=msgget(89,IPC_CREAT|0666))==-1)
{
printf("\n ERROR IN MSGGET");
exit(0);
}
printf("\n Enter the frame size:"); scanf("%d",&frmsz);
if((fp=fopen("check","r"))==NULL) printf("\n
FILE NOT OPENED");
else
printf("\n FILE OPENED");
while(!feof(fp))
{ d=getc(fp);
a[i]=d;
i++;
}
s=i;
for(i=0;i<frmsz;i++)
//print from the check file printf("\t %c",a[i]);
for(i=0;i<frmsz;i++)
{ if((msgrcv(msgid,&buf,sizeof(buf),0,1))==-1)
{
printf("\n ERROR IN MSGRCV");
exit(0);
}
printf("\n RECEIVED FRAMES ARE:%c",buf.mtext[i]);
}
for(i=0;i<frmsz;i++)
{ if(a[i]==buf.mtext[i])
count++;
} if(count==0)
{
printf("\n FRAMES WERE NOT RECEIVED IN CORRECT SEQ");
exit(0);
} if(count==frmsz)
{
printf("\n FRAMES WERE RECEIVED IN CORRECT SEQ");
} else
SEC CSE/V NETWORKS LAB MANUAL
44
{
printf("\n FRAMES WERE NOT RECEIVED IN CORRECT SEQ");
}}
Sliding Window Protocol -
Server
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mymsgbuf
{ long mtype;
char mtext[25];
};
FILE *fp;
int main()
{s
truct mymsgbuf buf;
int si,ei,sz; int
msgid; int i=0,s;
int a[100]; char d;
if((fp=fopen("send","r"))==NULL)
printf("\n FILE NOT OPENED"); else
printf("\n FILE OPENED");
printf("\n Enter starting and ending index of frame array:");
scanf("%d%d",&si,&ei); sz=ei-si;
if((msgid=msgget(89,IPC_CREAT|0666))==-1)
{
printf("\n ERROR IN MSGGET");
exit(0);
}
while(!feof(fp))
{ d=getc(fp);
a[i]=d;
i++;
}s
=i; buf.mtype=1;
for(i=si;i<=ei;i++)
{
buf.mtext[i]=a[i];
}
for(i=si;i<=ei;i++) //the frames to be sent
SEC CSE/V NETWORKS LAB MANUAL
45
printf("\t %c",buf.mtext[i]); for(i=0;i<=sz;i++)
{ if((msgsnd(msgid,&buf,sizeof(buf),0))==-1)
{
printf("\n ERROR IN MSGSND");
exit(0);
}}
printf("\n FRAMES SENT");
return 0;
}
OUTPUT:
Enter the frame size : 5
File opened
Enter starting & ending index of frame array : 0 9
Frames sent
Received frames are: 0 3 6 7 9
RESULT:
Thus the above program sliding window protocol was executed and successfully.
VIVA QUESTIONS
1.What is sliding window protocol?
A sliding window protocol is a feature of packet-based data transmission protocol.
Sliding window protocols are used where reliable in-order delivery of packets is
required, such as in the data link layer of OSI model as well as in the TCP.
2.What is data frame?
A data frame is an aggregate of numerous, partly overlapping collections of data and
metadata that have been derived from massive amounts of network activity such as
content production, consumption, and other user behavior.
SEC CSE/V NETWORKS LAB MANUAL
46
EX NO: 6
SIMULATION OF ROUTING PROTOCOL(BGP)
DESCRIPTION ABOUT THE EXPERIMENT
To simulate the implementation of the routing protocol BGP (Border Gateway Protocol)
Objective
Many nodes are obtained to check which node has the shortest path to source node . The
measures compared are cost of the node matrix and the minimum distance.
How it is being achieved?
Read n number of nodes and the cost for the node matrix is found. Make one
node as source node.Compute the minimum distance of each node with the source node. Then
the node with shortest path to source node is printed as result.
Syntax & keywords
To get number of nodes
printf("\n Enter the number of nodes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\n Enter the distance between the host %d - %d:",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
HOW TO EXECUTE THE SOURCE CODE
SEC CSE/V NETWORKS LAB MANUAL
47
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler C
EXPECTED OUTPUT AND ITS FORM
This program implements BGP to get host cost matrix and path as input and identifies
the shortest path from source as output .
ALGORITHM
1. Read the no. of nodes n.
2. Read the cost matrix for the path from each node to another node.
3. Initialize SOURCE to 1 and include 1.
4. Compute D of a node which is the distance from source to that corresponding
node.
5. Repeat step 6 to step 8 for n-l nodes.
6. Choose the node that has not been included whose distance is minimum and
include that node.
7. For every other node not included compare the distance directly from the source
with the distance to reach the node using the newly included node.
8. Take the minimum value as the new distance.
9. Print all the nodes with shortest path cost from source node.
Program :
#include <stdio.h>
#include<conio.h>
int main()
{
int n;
int i,j,k;
int a[10][10],b[10][10];
printf("\n Enter the number of nodes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
SEC CSE/V NETWORKS LAB MANUAL
48
printf("\n Enter the distance between the host %d - %d:",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>a[i][k]+a[k][j])
{
a[i][j]=a[i][k]+a[k][j];
}
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{ b[i][j]=a[i][j];
if(i==j)
{
b[i][j]=0;
}
}}
printf("\n The output matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
getch();
}
SEC CSE/V NETWORKS LAB MANUAL
49
OUTPUT
Enter the number of nodes: 5
Enter the distance between the host: 10
The output matrix :
10 15 20 25 30
RESULT:
Thus the above program to simulate the Implementing Routing Protocols using border
gateway protocol was executed and successfully.
VIVA QUESTIONS
1. What is protocol?
A standard set of regulations and requirements that allow two nodes to connect to
and exchange information with one another
2. What is BGP?
Border Gateway Protocol (BGP) is the protocol which is used to make core routing
decisions on the internet ; it involves a table of IP networks or "prefixes" which
designate network reachability among autonomous sytem (AS).
SEC CSE/V NETWORKS LAB MANUAL
50
EX NO: 7
IMPLEMENTING MAC PROTOCOL (ARP)
DESCRIPTION ABOUT THE EXPERIMENT
To get the MAC or Physical address of the system using Address Resolution Protocol.
Objective
The node is obtained from the user and IP address of each node is checked for its
validitiy.If it is a valid IP address then the MAC address is generated for that node.
How it is being achieved?
IP address of the node is obtained from the socket address and stored in
ARPREQ structure. Calculate the MAC address for the given IP Address using
ioctl() system call.
Syntax & keywords
To get error if ARP Cache is Empty:
if(ioctl(sd,SIOCGARP,&myarp)==1)
{
printf("No entry in ARP cache for%s",argv[1]);
exit(0);
}
HOW TO EXECUTE THE SOURCE CODE
SEC CSE/V NETWORKS LAB MANUAL
51
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler C
EXPECTED OUTPUT AND ITS FORM
The node is obtained from the user as input and IP address of each node is
checked for its validity. If it is a valid IP address then the MAC address is generated for that
node as output.
ALGORITHM
1. Include necessary header files.
2. Initialize the arpreq structure initially to zero.
3. Get the IPAddress of the system as command line argument.
4. Check whether the given IPAddress is valid.
5. Copy the IPAddress from sockaddr_in structure to arpreq structure using miscopy
()
system call.
6. Create a socket of type SOCK_DGRAM.
7. Calculate the MAC address for the given IPAddress using ioctl() system call.
8. Display the IPAddress and MAC address in the standard output.
Program:
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<net/if_arp.h>
#include<stdlib.h>
#include<stdio.h>
#include<netdb.h>
#include<sys/ioctl.h>
#include<arpa/inet.h>
int main(int argc,char *argv[])
{ int sd;
unsigned char *ptr;
SEC CSE/V NETWORKS LAB MANUAL
52
struct arpreq myarp={{0}};
struct sockaddr_in sin={0};
sin.sin_family=AF_INET;
if(inet_aton(argv[1],&sin.sin_addr)==0)
{
printf("IP address Entered%s is not valid\n",argv[1]);
exit(0);
} memcpy(&myarp.arp_pa,&sin,sizeof(myarp.arp_pa));
strcpy(myarp.arp_dev,"eth0");
sd=socket(AF_INET,SOCK_DGRAM,0);
if(ioctl(sd,SIOCGARP,&myarp)==1)
{
printf("No entry in ARP cache for%s",argv[1]);
exit(0);
} ptr=&myarp.arp_ha.sa_data[0];
printf("MAC address for%s",argv[1]);
printf("%x%x%x%x%x%x\n",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5));
return(0);
}
OUTPUT
IP Address entered is: 172.17.1.82
MAC Address for 172.17.1.82 is 172620
RESULT:
Thus the MAC address was generated for IP address using ARP protocol.
VIVA QUESTIONS
1.What is ARP?
Address Resolution Protocol (ARP) is a telecommunication protocol used for resolution
of network layer addresses into link layer addresses, a critical function in multiple-access
networks. ARP was defined by in 1982. It is also the name of the program for manipulating
these addresses in most operating systems.
2.Define MAC?
A media access control address (MAC address) is a unique identifier assigned to
network interface controller for communications on the physical network segment.
SEC CSE/V NETWORKS LAB MANUAL
53
NO: 8
IMPLEMENTING ROUTING PROTOCOL (OSPF)
DESCRIPTION ABOUT THE EXPERIMENT
To simulate the OPEN SHORTEST PATH FIRST routing protocol based on the cost
assigned to the path.
Objective
Many nodes are obtained to check which node has the shortest path to source node . The
measures compared are cost of the node matrix and the minimum distance.
How it is being achieved?
Read n number of nodes and the cost for the node matrix is found. Make one
node as source node.Compute the minimum distance of each node with the source node. Then
the node with shortest path to source node is printed as result.
Syntax & keywords
To find the shortest path:
void shortest()
{
int i,j,k;
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{ if(a[i][k]+a[k][j]<a[i][j])
a[i][j]=a[i][k]+a[k][j];
}
}
HOW TO EXECUTE THE SOURCE CODE
SEC CSE/V NETWORKS LAB MANUAL
54
REQUIREMENTS FOR EXECUTION
S.No. Facilities required Quantity
1 System 1
2 O/S Windws 98
3 Compiler C
EXPECTED OUTPUT AND ITS FORM
This program implements OSPF to get the list of nodes as input and to display the nodes
list with shortest path distance to the source as output.
ALGORITHM
1. Read the no. of nodes n.
2. Read the cost matrix for the path from each node to another node.
3. Initialize SOURCE to 1 and include 1.
4. Compute D of a node which is the distance from source to that corresponding node.
5. Repeat step 6 to step 8 for n-l nodes.
6. Choose the node that has not been included whose distance is minimum and
include that node.
7. For every other node not included compare the distance directly from the source
with the distance to reach the node using the newly included node.
8. Take the minimum value as the new distance.
9. Print all the nodes with shortest path cost from source node
SEC CSE/V NETWORKS LAB MANUAL
55
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[5][5],n,i,j;
void main()
{
void getdata();
void shortest();
void display();
clrscr();
printf("\n\n PROGRAM TO FIND SHORTEST PATH BETWEEN TWO
NODES\n");
getdata();
shortest();
display();
getch();
}
void getdata()
{
clrscr();
printf("\n\nENTER THE NUMBER OF HOST IN THE GRAPH\n");
scanf("%d",&n);
printf("\n\nIF THERE IS NO DIRECT PATH \n");
printf(" \n\nASSIGN THE HIGHEST DISTANCE VALUE 1000 \n");
for(i=0;i<n;i++)
{ a[i][j]=0;
for(j=0;j<n;j++)
{
if(i!=j)
{
printf("\n\nENTER THE DISTANCE BETWENN (%d,
%d): ",i+1,j+1);
scanf("%d",&a[i][j]);
if(a[i][j]==0)
a[i][j]=1000;
}
}
}
}
void shortest()
{
int i,j,k;
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{ if(a[i][k]+a[k][j]<a[i][j])
a[i][j]=a[i][k]+a[k][j];
}
SEC CSE/V NETWORKS LAB MANUAL
56
}
void display()
{
int i,j;
for(i=0;i<n;i
++)
for(j=0;j<n;j
++) if(i!=j)
{
printf("\n SHORTEST PATH IS : (%d,%d)--%d\n",i+1,j+1,a[i][j]);
}
getch(); }
OUTPUT
PROGRAM TO FIND SHORTEST PATH BETWEEN TWO NODES
ENTER THE NO OF HOST IN GRAPH 5 //( 10 18 15 30 35 )
THERE IS NO DIRECT PATH
ASSIGN THE HIGHEST DISTANCE VALUE 1000
ENTER THE DISTANCE BETWEEN NODES 10
SHORTEST PATH IS : 18 //(TO SOURCE 15)
RESULT:
Thus the above program to simulate the Implementing Routing Protocols using open
shortest path first (OSPF) was executed and successfully
VIVA QUESTIONS
1. What is OSPF?
It is an Internet routing protocol that scales well, can route traffic along multiple
paths, and uses knowledge of an Internet's topology to make accurate routing decisions.
2.What is routing protocols?
A routing protocol specifies how router communicate with each other, disseminating
information that enables them to select routes between any two node on a network.
SEC CSE/V NETWORKS LAB MANUAL
57
EX NO: 9
STUDY OF TCP/UDP PERFORMANCE
Introduction
Most network games use the User Datagram Protocol (UDP) as the underlying
transport protocol. The Transport Control Protocol (TCP), which is what most Internet
traffic relies on, is a reliable connection-oriented protocol that allows data streams
coming from a machine connected to the Internet to be received without error by any
other machine on the Internet. UDP however, is an unreliable connectionless protocol
that does not guarantee accurate or unduplicated delivery of data.
Why do games use UDP?
TCP has proved too complex and too slow to sustain real-time game-play.
UDP allows gaming application programs to send messages to other programs with the
minimum of protocol mechanism. Games do not rely upon ordered reliable delivery of
data streams. What is more important to gaming applications is the prompt delivery of
data. UDP allows applications to send IP datagram to other applications without
having to establish a connection and than having to release it later, which increases the
speed of communication. UDP is described in RFC 768. The UDP segment shown above
consists of an 8-byte header followed by the data octets.
SEC CSE/V NETWORKS LAB MANUAL
58
The UDP segment shown above consists of an 8-byte header followed by the
data octets
Fields:
The source and destination ports identify the end points within the
source and destination machines. The source port indicates the port of the
sending process and unless otherwise stated it is the port to which a reply should
be sent to. A zero is inserted into it if it is not used. The UDP Length field shows
the length of the datagram in octets. It includes the 8-byte header and the data to be
sent.The UDP checksum field contains the UDP header, UDP data and the
pseudo-header shown above. The pseudo-header contains the 32-bit IP addresses
of the source and destination machines, the UDP protocol number and the byte
count for the UDP segment. The pseudo- header helps to find undelivered packets
or packets that arrive at the wrong address. However the pseudo-header violates the
protocol hierarchy because the IP addresses which are used in it belong to the IP
layer and not to the UDP layer.
UDP Latency
While TCP implements a form of flow control to stop the network from flooding
there is no such concept in UDP. This is because UDP does not rely on
acknowledgements to signal successful delivery of data. Packets are simply transmitted
one after another with complete disregard to event of the receiver being flooded.
Effects of EDP
As mentioned before the majority of the traffic on the Internet relies on TCP. With
SEC CSE/V NETWORKS LAB MANUAL
59
the explosive increase in the amount of gaming taking place on the Internet, and with
most of these games using UDP, there are concerns about the effects that UDP will
have on TCP traffic.
Broadcast Flooding
A broadcast is a data packet that is destined for multiple hosts. Broadcasts can
occur at the data link layer and the network layer. Data-link broadcasts are sent to all hosts
attached to a particular physical network. Network layer broadcasts are sent to all hosts
attached to a particular logical network. The Transmission Control Protocol/Internet
Protocol (TCP/IP) supports the following types of broadcast packets:
All onesBy setting the broadcast address to all ones (255.255.255.255), all hosts on
the network receive the broadcast.
NetworkBy setting the broadcast address to a specific network number in the
network portion of the IP address and setting all ones in the host portion of the broadcast
address, all hosts on the specified network receive the broadcast. For example, when a
broadcast packet is sent with the broadcast address of 131.108.255.255, all hosts on
network number 131.108 receive the broadcast.
SubnetBy setting the broadcast address to a specific network number and a
specific subnet number, all hosts on the specified subnet receive the broadcast. For
example, when a broadcast packet is set with the broadcast address of 131.108.4.255, all
hosts on subnet 4 of network 131.108 receive the broadcast. Because broadcasts are
recognized by all hosts, a significant goal of router configuration is to control
unnecessary proliferation of broadcast packets.
Cisco routers support two kinds of broadcasts:directed and flooded. A
directed broadcast is a packet sent to a specific network or series of networks, whereas
a flooded broadcast is a packet sent to every network. In IP internetworks, most
broadcasts take the form of User Datagram Protocol (UDP) broadcasts. Although current
IP implementations use a broadcast address of all ones, the first IP implementations used
a broadcast address of all zeros. Many of the early implementations do not recognize
broadcast addresses of all ones and fail to respond to the broadcast correctly. Other
early implementations forward broadcasts of all ones, which causes a serious network
overload known as a broadcast storm.
SEC CSE/V NETWORKS LAB MANUAL
60
Implementations that exhibit these problems include systems based on versions
of BSD UNIX prior to Version 4.3. In the brokerage community, applications use
UDP broadcasts to transport market data to the desktops of traders on the trading floor.
This case study gives examples of how brokerages have implemented both directed
and flooding broadcast schemes in an environment that consists of Cisco routers and Sun
workstations. Note that the addresses in this network use a 0-bit netmask of
255.255.255.192.
SEC CSE/V NETWORKS LAB MANUAL
61
CHAPTER VI
EXPERIMENTS BEYOND THE SYLLABUS
EX NO: A
CLIENT-SERVER APPLICATION FOR CHAT
AIM:
To implement a chat server and client in java using TCP sockets.
ALGORITHM:
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop
Client
1. Create a client socket and connect it to the servers port number
2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop
PROGRAM:
// TCP Chat Server--tcpchatserver.java
import java.io.*;
import java.net.*;
class tcpchatserver
{
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser, fromClient;
try
{
ServerSocket Srv = new ServerSocket(5555);
SEC CSE/V NETWORKS LAB MANUAL
62
System.out.print("\nServer started\n");
Socket Clt = Srv.accept();
System.out.println("Client connected");
toClient = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals("end"))
break;
else
{
System.out.println("\nServer <<< " +CltMsg);
System.out.print("Message to Client : ");
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
}
catch (Exception E)
{
System.out.println(E.getMessage());
}
}
}
// TCP Chat Client--tcpchatclient.java
import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{
SEC CSE/V NETWORKS LAB MANUAL
63
if (args.length > 1) {
System.out.println("Usage: java hostipaddr");
System.exit(-1);
}
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),5555);
else
Clt = new Socket(InetAddress.getByName(args[0]),5555);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
System.out.println("Type \"end\" to Quit");
while (true)
{
System.out.print("\nMessage to Server : ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals("end"))
break;
SrvMsg = fromServer.readLine();
System.out.println("Client <<< " + SrvMsg);
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
}}
}
OUTPUT
Server:
$ javac tcpchatserver.java
$ java tcpchatserver
Server started
Client connected
Server <<< hi
Message to Client : hello
Server <<< how r u?
Message to Client : fine
Server <<< me too
Message to Client : bye
Client Disconnected
Client: $ javac tcpchatclient.java
SEC CSE/V NETWORKS LAB MANUAL
64
$ java tcpchatclient
Type "end" to Quit
Message to Server : hi
Client <<< hello
Message to Server : how r u?
Client <<< fine
Message to Server : me too
Client <<< bye
Message to Server : end
RESULT
Thus both the client and server exchange data using TCP socket programming.
SEC CSE/V NETWORKS LAB MANUAL
65
EX NO: B
UDP CHAT SERVER/CLIENT
AIM
To implement a chat server and client in java using UDP sockets.
ALGORITHM
Server
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to client port.
3. Create a datagram packet to receive client message.
4. Wait for client's data and accept it.
5. Read Client's message.
6. Get data from user.
7. Create a datagram packet and send message through server port.
8. Repeat steps 3-7 until the client has something to send.
9. Close the server socket.
10. Stop.
Client
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to server port.
3. Get data from user.
4. Create a datagram packet and send data with server ip address and client port.
5. Create a datagram packet to receive server message.
6. Read server's response and display it.
7. Repeat steps 3-6 until there is some text to send.
8. Close the client socket.
9. Stop.
PROGRAM
// UDP Chat Server--udpchatserver.java
import java.io.*;
import java.net.*;
class udpchatserver
{
public static int clientport = 8040,serverport = 8050;
public static void main(String args[]) throws Exception
{
DatagramSocket SrvSoc = new DatagramSocket(clientport);
SEC CSE/V NETWORKS LAB MANUAL
66
byte[] SData = new byte[1024];
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Server Ready");
while (true)
{
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,
RData.length);
SrvSoc.receive(RPack);
String Text = new String(RPack.getData());
if (Text.trim().length() == 0)
break;
System.out.println("\nFrom Client <<< " + Text );
System.out.print("Msg to Cleint : " );
String srvmsg = br.readLine();
InetAddress IPAddr = RPack.getAddress();
SData = srvmsg.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,
SData.length, IPAddr, serverport);
SrvSoc.send(SPack);
}
System.out.println("\nClient Quits\n");
SrvSoc.close();
}
}
// UDP Chat Client--udpchatclient.java
import java.io.*;
import java.net.*;
class udpchatclient
{
public static int clientport = 8040,serverport = 8050;
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new
InputStreamReader (System.in));
DatagramSocket CliSoc = new DatagramSocket(serverport);
InetAddress IPAddr;
String Text;
if (args.length == 0)
IPAddr = InetAddress.getLocalHost();
else
IPAddr = InetAddress.getByName(args[0]); byte[]
SData = new byte[1024]; System.out.println("Press
Enter without text to quit"); while (true)
{
System.out.print("\nEnter text for server : ");
SEC CSE/V NETWORKS LAB MANUAL
67
Text = br.readLine();
SData = Text.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,
SData.length, IPAddr, clientport );
CliSoc.send(SPack);
if (Text.trim().length() == 0)
break;
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,
RData.length);
CliSoc.receive(RPack);
String Echo = new String(RPack.getData()) ;
Echo = Echo.trim();
System.out.println("From Server <<< " + Echo);
}
CliSoc.close();
}
}
OUTPUT
Server
$ javac udpchatserver.java
$ java udpchatserver
Server Ready
From Client <<< are u the SERVER
Msg to Cleint : yes
From Client <<< what do u have to serve
Msg to Cleint : no eatables
Client Quits
Client
$ javac udpchatclient.java
$ java udpchatclient
Press Enter without text to quit
Enter text for server : are u the SERVER
From Server <<< yes
Enter text for server : what do u have to serve
From Server <<< no eatables
Enter text for server :
RESULT
Thus both the client and server exchange data using UDP sockets.
SEC CSE/V NETWORKS LAB MANUAL
68
EX NO: C
SIMPLE CALCULATOR USING RMI
AIM:
To implement simple calculator on a remote host and invoke operations from a client.
ALGORITHM:
Interface:
Declare server's remote interface for all calculator operation by extending Remote
interface
Implementation:
Define basic calculator operations such as summation, difference, product, quotient
And remainder by extending UnicastRemoteObject.
Server:
1.Create a calculator object
2.Register the object with the RMI registry on the server machine using rebind
method
Client
1.Obtain operands from the user
2.Lookup for the Calculator service on the remote server
3.Call all arithmetic operations on the remote server
4.Display result of various arithmetic operations.
SEC CSE/V NETWORKS LAB MANUAL
69
Procedure
1. Compile the four java files (Interface, Implementation, Server and Client)
2. Generate stub by compiling the implementation file using RMI compiler
3. Distribute the class files of Client, Interface and Stub to the clients
4. Start the RMI registry on the server
5. Start the server
6. Call procedures that exist on the remote host from client machine.
PROGRAM:
// Declares remote method interfaces--CalcInf.java
import java.rmi.*;
public interface CalcInf extends Remote
{
public long add(int a, int b) throws RemoteException;
public int sub(int a, int b) throws RemoteException; public
long mul(int a, int b) throws RemoteException; public int
div(int a, int b) throws RemoteException; public int
rem(int a, int b) throws RemoteException;
}
// Implement Remote behavior--CalcImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class CalcImpl extends UnicastRemoteObject implements
CalcInf
{
public CalcImpl() throws RemoteException { }
public long add(int a, int b) throws RemoteException
{
return a + b;
}
public int sub(int a, int b) throws RemoteException
{
int c = a > b ? a - b : b - a;
return c;
}
public long mul(int a, int b) throws RemoteException
{
return a * b;
}
public int div(int a, int b) throws RemoteException
{
SEC CSE/V NETWORKS LAB MANUAL
70
return a / b;
}
public int rem(int a, int b) throws RemoteException
{
return a % b;
}
}
// Server that names the service implemented--CalcServer.java
import java.rmi.*;
public class CalcServer
{
public static void main(String args[])
{
try
{
CalcInf C = new CalcImpl();
Naming.rebind("CalcService", C);
}
catch (Exception e)
{ System.out.println(e.getMessage());
}
}
}
// Client that invokes remote host methods--CalcClient.java
import java.rmi.*;
import java.net.*;
public class CalcClient
{
public static void main(String[] args) throws Exception
{
try
{
CalcInf C = (CalcInf) Naming.lookup("rmi://" +
args[0] + "/CalcService");
int a, b;
if (args.length != 3)
{
System.out.println("Usage: java CalcClient
<remoteip> <operand1> <operand2>");
System.exit(-1);
}
a = Integer.parseInt(args[1]); b =
SEC CSE/V NETWORKS LAB MANUAL
71
Integer.parseInt(args[2]); System.out.println(
"\nBasic Remote Calc\n" );
System.out.println("Summation : " + C.add(a, b));
System.out.println("Difference : " + C.sub(a, b));
System.out.println("Product : " + C.mul(a, b));
System.out.println("Quotient : " + C.div(a, b));
System.out.println("Remainder : " + C.rem(a, b));
}
catch (Exception E)
{ System.out.println(E.getMessage());
}
}
}
OUTPUT
Server
C:\>javac CalcInf.java
C:\>javac CalcImpl.java
C:\>javac CalcServer.java
C:\>javac CalcClient.java
C:\>rmic CalcImpl C:\>start
rmiregistry C:\>java
CalcServer
Client
C:\>java CalcClient 172.16.6.45
6 8
Basic Remote Calc
Summation : 14
Difference : 2
Product : 48
Quotient : 0
Remainder : 6
RESULT
Thus remote procedure calls for basic operations of a calculator is executed using
Java RMI.