CN Lab
CN Lab
– 1
AIM: Implementation of Stop and Wait Protocol and Sliding CO1, PO1, PO2, PO3,
Window Protocol. PO4, PO5, PO11, PO12
Objective:
In this lab session, you will learn about the implementation of Stop and Wait Protocol and Sliding Window
Protocol.
Tasks:
Stop and Wait Protocol is the simplest flow control method in which the sender will send the packet and then wait
for
the acknowledgement by the receiver that it has received the packet then it will send the next packet. Stop and
wait protocol is very easy to implement.
Design
1
• Sender Site: The data link layer in the sender site waits for the network layer for a data packet. It then
checks whether it can send the frame. If it receives a positive notification from the physical layer, it
makes frames out of the data and sends it. It then waits for an acknowledgement before sending the
next frame.
• Receiver Site: The data link layer in the receiver site waits for a frame to arrive. When it arrives, the
receiver processes it and delivers it to the network layer. It then sends an acknowledgement back to the
sender.
Algorithm: Sender Site Algorithm of Simplex Stop – and – Wait Protocol for Noiseless Channel
begin
canSend = True; //Allow the first frame to be sent
while (true) //check repeatedly
do
Wait_For_Event(); //wait for availability of packet
if ( Event(Request_For_Transfer) AND canSend) then
Get_Data_From_Network_Layer();
Make_Frame();
Send_Frame_To_Physical_Layer();
canSend = False;
else if ( Event(Acknowledgement_Arrival)) then
Receive_ACK();
canSend = True;
end if
end while
end
Algorithm: Receiver Site Algorithm of Simplex Stop – and – Wait Protocol for Noiseless Channel
begin
while (true) //check repeatedly
do
Wait_For_Event(); //wait for arrival of frame
if ( Event(Frame_Arrival) then
Receive_Frame_From_Physical_Layer();
Extract_Data();
Deliver_Data_To_Network_Layer();
Send_ACK();
end if
end while
end
2
Algorithm : Sliding Window Protocol
In computer networks sliding window protocol is a method to transmit data on a network. Sliding window
protocol is applied on the Data Link Layer of OSI model. At data link layer data is in the form of frames. In
Networking, Window simply means a buffer which has data frames that needs to be transmitted.
Both sender and receiver agrees on some window size. If window size=w then after sending w frames sender
waits for the acknowledgement (ack) of the first frame.
As soon as sender receives the acknowledgement of a frame it is replaced by the next frames to be
transmitted by the sender. If receiver sends a collective or cumulative acknowledgement to sender then it
understands that more than one frames are properly received, for eg:- if ack of frame 3 is received it
understands that frame 1 and frame 2 are received properly.
In sliding window protocol the receiver has to have some memory to compensate any loss in transmission or
if the frames are received unordered.
3
Sliding Window Protocol Program in C
#include<stdio.h>
int main()
{
int w,i,f,frames[50];
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);
printf("\nWith sliding window protocol the frames will be sent in the following manner (assuming no corruption of
frames)\n\n");
printf("After sending %d frames at each stage sender waits for acknowledgement sent by the receiver\n\n",w);
for(i=1;i<=f;i++)
{
if(i%w==0)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by sender\n\n");
}
else
printf("%d ",frames[i]);
}
if(f%w!=0)
printf("\nAcknowledgement of above frames sent is received by sender\n");
return 0;
}
Output
5
EXPERIMENT NO. – 2
AIM: Study of Socket Programming and Client – Server model CO1, PO1, PO2, PO3,
PO4, PO5, PO11, PO12
Objective:
This lab session focuses on Study of Socket Programming and Client – Server model.
Tasks:
❖ Socket
A socket is formally defined as an endpoint for communication between an application program, and the
underlying network protocols.
The two modes of services available are
• Connection-oriented service
• Connection less service
CONNECTION-LESS
In a connection –less mode an application program sends its data immediately without waiting for
connection establishment. As a result the application program may waste its time by sending data when the other
end is not ready to accept it. Moreover,data may not arrive at the other end if the network decides to discards it.
If data arrives at the destination, it may not arrive in the same order as it was transmitted.
The connectionless mode is often said to provide best effort service, since the network would try its best
to deliver the information but cannot guarantee the delivery.
The figure shows the sequence of system calls for a connectionless communication. No connection is established
prior to data transfer. The recvfrom call returns when a Complete UDP data gram has been received.
Socket system calls for connection less service
▪ The following figure illustrates the example of client/server relationship of the socket APIs for a
connectionless protocol (UDP).
7
Simple Echo Client Server Using UDP:
stdin fgets Send to recvfrom
UDP UDP
stdout fput Client recvfromsendto Server
❖ Types of sockets
➢ Stream sockets
➢ Datagram sockets and
➢ Raw sockets
Stream sockets are used for stream connections, i.e. connections that exist for a long duration. TCP connections
use stream sockets.
Datagram sockets are used for short-term connections that transfer a single packet across the network before
terminating. The UDP protocol uses such sockets, due to its connection-less nature.
Raw sockets are used to access low-level protocols directly, bypassing the higher protocols. They are the means
for a programmer to use the IP protocol, or the physical layer of the network, directly. Raw sockets can therefor
be used to implement new protocols on top of the low-level protocols. Naturally, they are out of our scope.
8
connect() Initiate a connection to a remote host.
recv() Receive data from a socket descriptor.
send() Send data to a socket descriptor.
read() Reads from files, devices, sockets etc.
write() Writes to files, devices, sockets etc.
close() “One-way” close of a socket descriptor.
Allows you to cut off communication in a certain direction, or both ways
shutdown() just like close() does.
Socket API Functions
Socket API functions
socket()
socket() creates an endpoint for communication and returns a file descriptor for the socket. socket() takes three
arguments:
• domain, which specifies the protocol family of the created socket. For example:
o PF_INET for network protocol IPv4 or
o PF_INET6 for IPv6.
o PF_UNIX for local socket (using a file).
• type, one of:
o SOCK_STREAM (reliable stream-oriented service or Stream Sockets)
o SOCK_DGRAM (datagram service or Datagram Sockets)
o SOCK_SEQPACKET (reliable sequenced packet service), or
o SOCK_RAW (raw protocols atop the network layer).
• protocol specifying the actual transport protocol to use. The most common are IPPROTO_TCP,
IPPROTO_SCTP, IPPROTO_UDP, IPPROTO_DCCP. These protocols are specified in
<netinet/in.h>. The value “0” may be used to select a default protocol from the selected domain and
type.
The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly-assigned
descriptor.
Prototype
int socket(int domain,int type,int protocol);
bind()
9
bind() assigns a socket an address. When a socket is created using socket(), it is only given a protocol family, but
not assigned an address. This association with an address must be performed with the bind() system call before
the socket can accept connections to other hosts. bind() takes three arguments:
Prototype
int bind(intsockfd,conststructsockaddr*my_addr,socklen_taddrlen);
listen()
After a socket has been associated with an address, listen() prepares it for incoming connections. However, this
is only necessary for the stream-oriented (connection-oriented) data modes, i.e., for socket types (SOCK_STREAM,
SOCK_SEQPACKET). listen() requires two arguments:
Prototype
int listen(intsockfd,int backlog);
accept()
When an application is listening for stream-oriented connections from other hosts, it is notified of such events
(cf. select() function) and must initialize the connection using the accept() function. Accept() creates a new socket
for each connection and removes the connection from the listen queue. It takes the following arguments:
• sockfd, the descriptor of the listening socket that has the connection queued.
• cliaddr, a pointer to a sockaddr structure to receive the client's address information.
• addrlen, a pointer to a socklen_t location that specifies the size of the client address structure passed to
accept(). When accept() returns, this location indicates how many bytes of the structure were actually
used.
10
The accept() function returns the new socket descriptor for the accepted connection, or -1 if an error occurs. All
further communication with the remote host now occurs via this new socket.
Datagram sockets do not require processing by accept() since the receiver may immediately respond to the request
using the listening socket.
Prototype
int accept(intsockfd,structsockaddr*cliaddr,socklen_t*addrlen);
connect()
The connect() system call connects a socket, identified by its file descriptor, to a remote host specified by that
host's address in the argument list.
Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For these sockets,
connect takes on a special meaning: the default target for sending and receiving data gets set to the given address,
allowing the use of functions such as send() and recv() on connectionless sockets.
connect() returns an integer representing the error code: 0 represents success, while -1 represents an error.
Prototype
int connect(intsockfd,conststructsockaddr*serv_addr,socklen_taddrlen);
❖ Sending and receiving data over a socket
After a connection is established, there are several ways to send information over the socket.
read()
The most common way of reading data from a socket is using the read () system call, which is defined like this:
11
Note that read() might read less than the number of bytes we requested, due to unavailability of buffer space in
the system.
write()
The most common way of writing data to a socket is using the write() system call, which is defined like this:
Note that the system keeps internal buffers, and the write system call write data to those buffers, not necessarily
directly to the network. Thus, a successful write() doesn't mean the data arrived at the other end, or was even sent
onto the network. Also, it could be that only some of the bytes were written, and not the actual number we
requested. It is up to us to try to send the data again later on, when it's possible, and we'll show several methods
for doing just that.
▪ Since datagram sockets aren’t connected to a remote host, we need to give the destination address before
we send a packet.
▪ The prototype is:
intsendto(intsockfd, const void *msg, intlen, unsigned int flags, const
structsockaddr *to, inttolen);
▪ This call is basically the same as the call to send() with the addition of two other pieces of information.
▪ to is a pointer to a structsockaddr (which you’ll probably have as a structsockaddr_in and cast it at the
last minute) which contains the destination IP address and port.
▪ tolen can simply be set to sizeof(structsockaddr).
▪ Just like with send(), sendto() returns the number of bytes actually sent (which, again, might be less than
the number of bytes you told it to send!), or -1 on error.
Socket Address
structsockaddr_in
structsockaddr_in {
u_charsin_len;
u_shortsin_family; // Address family
u_shortsin_port; // Port number
struct in_addrsin_addr; // Internet or IP address
char sin_zero[8]; // Same size as structsockaddr
};
• The sin_family field is the address family (always AF_INET for TCP and UDP).
• The sin_port field is the port number, and the sin_addr field is the Internet address. The sin_zero field is
reserved, and you must set it to hexadecimal zeroes.
• Data type structin_addr - this data type is used in certain contexts to contain an Internet host address. It
has just one field, named s_addr, which records the host address number as an unsigned long int.
• sockaddr_in is a "specialized" sockaddr.
• sin_addr could be u_long.
• sin_addr is 4 bytes and 8 bytes are unused.
• sockaddr_in is used to specify an endpoint.
• The sin_port and sin_addr must be in Network Byte Order.
13
EXPERIMENT NO. – 3
AIM: Write a code simulating ARP /RARP protocols. CO1, PO1, PO2, PO3,
PO4, PO5, PO11, PO12
Objective:
In this lab session, you will learn to simulate ARP /RARP protocols
Tasks:
Address Resolution Protocol (ARP) – Address Resolution Protocol is a communication protocol used
for discovering physical address associated with given network address. Typically, ARP is a network
layer to data link layer mapping process, which is used to discover MAC address for given Inter net
Protocol Address.
In order to send the data to destination, having IP address is necessary but not sufficient; we also need
the physical address of the destination machine. ARP is used to get the physical address (MAC
address) of destination machine.
Before sending the IP packet, the MAC address of destination must be known. If not so, then sender broadcasts
the ARP-discovery packet requesting the MAC address of intended destination. Since ARP-discovery is
broadcast, every host inside that network will get this message but the packet will be discarded by everyone
except that intended receiver host whose IP is associated. Now, this receiver will send a unicast packet with its
MAC address (ARP-reply) to the sender of ARP-discovery packet. After the original sender receives the ARP-
reply, it updates ARP-cache and start sending unicast message to the destination.
14
Reverse Address Resolution Protocol (RARP) –
Reverse ARP is a networking protocol used by a client machine in a local area network to request its Internet
Protocol address (IPv4) from the gateway-router’s ARP table. The network administrator creates a table in
gateway-router, which is used to map the MAC address to corresponding IP address.
When a new machine is setup or any machine which don’t have memory to store IP address, needs an IP address
for its own use. So the machine sends a RARP broadcast packet which contains its own MAC address in both
sender and receiver hardware address field.
A special host configured inside the local area network, called as RARP-server is responsible to reply for these
kind of broadcast packets. Now the RARP server attempt to find out the entry in IP to MAC address mapping
table. If any entry matches in table, RARP server send the response packet to the requesting device along with
IP address.
• LAN technologies like Ethernet, Ethernet II, Token Ring and Fiber Distributed Data Interface (FDDI)
support the Address Resolution Protocol.
• RARP is not being used in today’s networks. Because we have much great featured protocols like BOOTP
(Bootstrap Protocol) and DHCP( Dynamic Host Configuration Protocol).
//ARP SERVER
#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
15
#include<string.h>
main()
{
int shmid, a, i;
char *ptr, *shmptr;
shmid=shmget(3000,10,IPC_CREAT | 0666);
shmptr=shmat(shmid,NULL,0);
ptr=shmptr;
for(i=0;i<3;i++)
{
puts("enter the mac");
scanf("%s",ptr);
a=strlen(ptr);
printf("string length:%d",a);
ptr[a]= ' ' ;
puts("enter ip");
ptr=ptr+a+1;
scanf("%s",ptr);
ptr[a]='\n' ;
ptr= ptr+a+1;
}
ptr[strlen(ptr)]= '\0';
printf("\n ARP table at serverside is=\n%s", shmptr);
shmdt(shmptr);
}
//ARP CLIENT
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/shm.h>
main()
{
int shmid,a;
char *ptr, *shmptr;
char ptr2[51], ip[12], mac[26];
shmid=shmget(3000,10,0666);
shmptr=shmat(shmid,NULL,0);
puts("the arp table is");
printf("%s",shmptr);
printf("\n1.ARP\n 2.RARP\n 3.EXIT\n");
scanf("%d",&a);
switch(a)
16
{
case 1:
puts("enter ip address");
scanf("%s",ip);
ptr=strstr(shmptr, ip);
ptr-=8;
sscanf(ptr,"%s%*s",ptr2);
printf("mac addr is %s",ptr2);
break;
case 2:
puts("enter mac addr");
scanf("%s",mac);
ptr=strstr(shmptr, mac);
sscanf(ptr,"%*s%s",ptr2);
printf("%s",ptr2);
break;
case 3:
exit(1);
}}
1.ARP
2.RARP
3.EXIT
enter your choice: 1
enter ip address: 1.2.3.4
mac addr is a.b.c.d
17
EXPERIMENT NO. – 4
AIM: Write a code simulating PING and TRACEROUTE CO1, PO1, PO2, PO3,
commands PO4, PO5, PO11, PO12
Objective:
This lab session simulate PING and TRACEROUTE commands.
Tasks:
In computer networks, data is sent in small blocks known as packets. Each packet is transmitted individually
and may also follow a different route to reach the destination. Once all these packets of the original message
reach the destination, they are re-assembled to form the original message. But, sometimes, it may happen that
the webserver is down, network congestion, or some other technical glitch is there, that may prevent the
message from reaching the destination. To diagnose such congestions and network failures, we use two
common programs namely Ping and Traceroute.
Ping – It is a utility that helps one to check if a particular IP address is accessible or not. Ping works by sending
a packet to the specified address and waits for the reply. It also measures round trip time and reports errors.
Ping is also used in checking if the computers on a local network are active. For this, the user has to go in
command prompt and type: ping 127.0.0.1, and if the address is active, the ping would return a message like
this :
Pinging 127.0.0.1 with 32 bytes of data
Reply from 127.0.0.1: bytes=32 time<10ms TTL=32
Reply from 127.0.0.1: bytes=32 time<10ms TTL=32
Reply from 127.0.0.1: bytes=32 time<10ms TTL=32
Reply from 127.0.0.1: bytes=32 time<10ms TTL=32
The IP address 127.0.0.1 is the address of the local host and would receive a ping reply even if the sender is
not connected to the internet.
Traceroute – It is a utility that traces a packet from your computer to the host, and will also show the number
of steps (hops) required to reach there, along with the time by each step. Traceroute works by sending the
packets of data with low survival time (Time to Live – TTL) which specifies how many steps (hops) can the
packet survive before it is returned. When a packet can’t reach the final destination and expires at an
intermediate step, that node returns the packet and identifies itself. So, by increasing the TTL gradually,
Traceroute is able to identify the intermediate hosts. If any of the hops come back with “Request timed out”,
it denotes network congestion and a reason for slow loading Web pages and dropped connections.
The main difference between Ping and Traceroute is that Ping is a quick and easy utility to tell if the specified
server is reachable and how long will it take to send and receive data from the server whereas Traceroute finds
the exact route taken to reach the server and time taken by each step (hop).
Algorithm:
Server
Step1: Start the program.
Step2: Import necessary packages.
Step3: Initialize the ping server with both sockets as null value.
18
Step4: Start the server socket.
Step5: At the client give the IP address of the server(by using ifconfig command in command prompt).
Step6: The client program is then started by starting socket.
Step7: At the receiver end, the client is pinged and traced. Step8: Stop the program.
Client
Step1: Start the program.
Step2: Import necessary packages.
Step3: Initialize the ping client with both sockets as null value.
Step4: Start the socket.
Step5: Get the IP address of the server.
Step6: Ping the server.
Step7: At the receiver end, the server is pinged and traced.
Step8: Stop the program.
pingclient.java
/*…localhostport name and 5555-port number…*/
Socket s=new Socket("127.0.0.1",5555);
/*… Get an input file handle from the socket and read the input…*/
DataInputStream dis=new DataInputStream(s.getInputStream()); PrintStream out=new
PrintStream(s.getOutputStream()); while(c<4){
…returns the current time in milliseconds…*/
t1=System.currentTimeMillis();
str="Welcome to network programming world";
out.println(str);
/*…readline() method read a line of text…*/
System.out.println(dis.readLine());
t2=System.currentTimeMillis();
System.out.println(";TTL="+(t2-t1)+"ms"); c++;
pingserver.java
19
Viva questions:
5.What utility is used to find the number of routers between a source and destination?
20
EXPERIMENT NO. – 5
AIM: Create a socket for HTTP for web page upload and CO1, PO1, PO2, PO3,
download. PO4, PO5, PO11, PO12
Objective:
In this lab session you create a socket for HTTP for web page upload and download.
Tasks:
Concept:
Concurrent Server: The server can be iterative, i.e. it iterates through each client and serves one request
at a time. Alternatively, a server can handle multiple clients at the same time in parallel, and this type ofa
server is called a concurrent server.
Algorithm:
Server
Step 1: Create a socket and bind to the address. Leave socket unconnected.
Step 2 : Leave socket in passive mode, making it ready for use by a server.
Step 3: Repeatedly call accept to receive the next request from a client to handle the response with the
through socket.
Client
Step 1: Begin with a connection passed from the server (i.e., a socket for the connection).
Step 2: Use input streams; get the message from user to be given to the server.
Step 3: Use input streams read message given by server and print it.
Step 4: Use output streams to write message to the server.
Step 5: Close the connection and exit, i.e., slave terminates after handling all requests from one client.
Sample Program:
ConServer.java
/*… Register service on port 8020…*/
ServerSocketss=new ServerSocket(8500);
System.out.println("Waiting for client..."); while(true)
/*... ServerSocket in order to listen for and accept connections from clients...*/
{Socket s=ss.accept();
/*…getInputStream()-This method take the permission to write the data from client program to
server program and server program to client program…*/
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
cli_name=br.readLine();
21
System.out.println("\nCLIENT NAME: "+cli_name);
no=Integer.parseInt(br.readLine());
sq=no*no;
PrintWriter pw=new PrintWriter(s.getOutputStream(),true); pw.println(sq);
System.out.println("OUTPUT - The square of "+no+" is "+sq);}}}
ConClient1.java
/*...Integer.parseInt() java method is used primarily in parsing a String method argument into
an Integer object. The Integer object is a wrapper class for the int primitive data type ...*/
int num=Integer.parseInt(br.readLine());
/* …getOutputStream()-This method is used to take the permission to read data from client
system by the server or from the server system by the client…*/
PrintWriterpw=new PrintWriter(s.getOutputStream(),true);
pw.println("Client 1");
pw.println(num);
BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));
intsqu=Integer.parseInt(br1.readLine());
System.out.println("Square of "+num+" is "+squ+"\n");
ConClient2.java
Socket s=new Socket("localhost",8500);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nCLIENT 2:\nEnter the number to find square: ");
intnum=Integer.parseInt(br.readLine());
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
pw.println("Client 2");
pw.println(num);
BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));
intsqu=Integer.parseInt(br1.readLine());
System.out.println("Square of "+num+" is "+squ+"\n"); s.close();
Sample Output:
22
Viva questions:
23
6. Explain socket address structure
7. List some character stream support classes
8. What do you mean by socket programming?
24
EXPERIMENT NO. – 6
AIM: Write a program to implement RPC (Remote Procedure CO1, PO1, PO2, PO3,
Call) PO4, PO5, PO11, PO12
Objective:
This lab session we implement RPC (Remote Procedure Call).
Tasks:
Remote Procedure Call (RPC) is a powerful technique for constructing distributed, client-server based
applications. It is based on extending the conventional local procedure calling so that the called procedure
need not exist in the same address space as the calling procedure. The two processes may be on the same
system, or they may be on different systems with a network connecting them .
1. The calling environment is suspended, procedure parameters are transferred across the network to the
environment where the procedure is to execute, and the procedure is executed there.
2. When the procedure finishes and produces its results, its results are transferred back to the calling
environment, where execution resumes as if returning from a regular procedure call.
This section addresses the C interface to RPC and describes how to write network applications using RPC. For a
complete specification of the routines in the RPC library, see the rpc and related man pages.
Simplified Interface
25
The simplified interface is the easiest level to use because it does not require the use of any other RPC routines.
It also limits control of the underlying communications mechanisms. Program development at this level can be
rapid, and is directly supported by the rpcgen compiler. For most applications, rpcgen and its facilities are
sufficient. Some RPC services are not available as C functions, but they are available as RPC programs. The
simplified interface library routines provide direct access to the RPC facilities for programs that do not require
fine levels of control.
Routines such as rusers are in the RPC services library librpcsvc. rusers.c, below, is a program that displays the
number of users on a remote host. It calls the RPC library routine, rusers.
Program:
#include"rpc/rpc.h"
#include"square.h"
#include"stdio.h"
#include"stdlib.h"
#include"math.h"
cl=clnt_create(argv[1],SQUARE_PROG,SQUARE_VERS,"tcp");
in.arg1=atol(argv[2]);
if(cl==NULL)
{
printf("\nerror:%s",strerror(errno));
exit(-1);
}
if((outp=squareproc_1(&in,cl))==NULL)
{
printf("\nerror :%s",clnt_sperror(cl,argv[1]));
exit(-1);
}
// .h FILENAME: square.h
struct square_in
{
/*input arg*/
long arg1;
27
};
struct square_out
{
/*op result*/
long res1;
};
program SQUARE_PROG
{
version SQUARE_VERS
{
square_out SQUAREPROC(square_in)=1; /*proc no=1*/
}=1; /*version no*/
}=0x31230000;/*prog no*/
Output:
[root@localhost~]#rpcgen -C square.x
[root@localhost~]#cc -c client.c -o client.o
[root@localhost~]#cc -c square_clnt.c -o square_clnt.o
[root@localhost~]#cc -c square_xdr.c -o square.xdr.o
[root@localhost~]#cc -o client client.o square_clnt.o square_xdr.o
[root@localhost~]#cc -c client.c server.c square_xdr.c
[root@localhost~]#cc -c server.c -o server.o
[root@localhost~]#cc -c square_svc.c -o square_svc.o
[root@localhost~]#cc -o server server.o square_svc.o square_xdr.o
[root@localhost~]#./server &
[1] 2264
[root@localhost~]#./client localhost 4
result is: 16
28
EXPERIMENT NO. – 7
AIM: Implementation of concept of Subnetting CO1, PO1, PO2, PO3,
PO4, PO5, PO11, PO12
Objective:
In this lab session, you will learn the Implementation of Subnetting
Tasks:
If an organization was granted a large block in class A or B, it could divide the addresses into several
contiguous groups and assign each group to smaller networks (called subnets) or, in rare cases, share part of
the addresses with neighbours.
Algorithm:
Step1: Get the input from the user by using scanner method.
Step 2: Read the input by using nextLine() and store it. Step 3:
Split the string based on string by using split(“\\”) Step4 :
Convert it into binary.
Step 5: calculating the network mask by using math and logarithmic
Step 6: get the first address by ANDding the last n bits with 0.
Step7 : get the last address by ANDding the last n bits with 1.
Sample Coding:
//…Calculation of mask…//
int bits = (int)Math.ceil(Math.log(n)/Math.log(2));
/*eg if address = 120, log 120/log 2 gives log to the base 2 => 6.9068, ceil gives us upper integer */
System.out.println("Number of bits required for address = "+bits);
int mask = 32-bits;
System.out.println("The subnet mask is = "+mask);
//…Calculation of first address and last address…//
intfbip[] = new int[32];
for(int i=0; i<32;i++) fbip[i] = (int)bip.charAt(i)-48;
//convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i--)//Get first address by ANDing last n bits with 0 fbip[i] &= 0;
String fip[] = {"","","",""};
for(int i=0;i<32;i++)
29
fip[i/8] = new String(fip[i/8]+fbip[i]);
System.out.print("First address is = ");
for(int i=0;i<4;i++)
{
System.out.print(Integer.parseInt(fip[i],2));
if(i!=3) System.out.print(".");
}
Sample Output:
Viva questions:
31
EXPERIMENT NO. –8(a)
AIM: Applications using TCP Sockets like Chat. CO1, PO1, PO2, PO3,
PO4, PO5, PO11, PO12
Objective:
This lab session we implement an Applications using TCP Sockets like Chat.
Tasks:
1. A server program to establish the socket connection with the client for performing chat.
2. A client program which on establishing a connection with the server for performing chat.
Concept:
It uses TCP socket communication .We have a server as well as a client.
Both can be run in the same machine or different machines. If both are running in the machine,
the address to be given at the client side is local host address.
If both are running in different machines, then in the client side we need to specify the ip address of machine
in which server application is running.
Algorithm:
Server
Step1: Start the program and create server and client sockets.
Step2: Use input streams to get the message from user.
Step3: Use output streams to send message to the client.
Step4: Wait for client to display this message and write a new one to be displayed by the server.
Step5: Display message given at client using input streams read from socket.
Step6: Stop the program.
Client
Step1: Start the program and create a client socket that connects to the required host and port.
Step2: Use input streams read message given by server and print it.
Step3: Use input streams; get the message from user to be given to the server.
Step4: Use output streams to write message to the server.
Step5: Stop the program.
32
Sample Program: GossipServer.java
GossipClient.java
Socket sock = new Socket("127.0.0.1", 3000);
34
EXPERIMENT NO. –8(b)
AIM: Applications using TCP Sockets like file Transfer CO1, PO1, PO2, PO3,
PO4, PO5, PO11, PO12
Objective:
This lab session we implement an Applications using TCP Sockets like file Transfer.
Tasks:
Algorithm
Server
Client
Sample Code:Se.java
{/*… Register service on port 15123…*/
ServerSocketserverSocket = new ServerSocket(15123);
Cl.java
Sample Output:
36
Viva questions:
37
EXPERIMENT NO. –9
AIM: Applications using TCP and UDP Sockets like DNS & CO1, PO1, PO2, PO3,
SNMP PO4, PO5, PO11, PO12
Objective:
This lab session we implement an Applications using TCP and UDP Sockets like DNS & SNMP.
Tasks:
1. The DNS client program sends a request to a DNS server to map the e-mail address to the
corresponding IP address.
2. When the Internet was small, mapping was done by using a host file. The host file had only two
columns: name and address.
3. The host that needs mapping can contact the closest computer holding the needed information. This
method is used by the Domain Name System (DNS).
Algorithm:
Server
Step1: Start the program.
Step2: Create the socket for the server.
Step3: Bind the socket to the port.
Step4: Listen for the incoming client connection.
Step5: Receive the IP address from the client to be resolved.
Step6: Get the domain name for the client.
Step7: Check the existence of the domain in the server.
Step8: If domain matches then send the corresponding address to the client.
Step9: Stop the program execution
Client
Step1: Start the Program.
Step2: Create the socket for the client.
Step3: Connect the socket to the Server.
Step4: Send the host name to the server to be resolved.
Step5: If the server corresponds then print the address and terminate the process
Sample Program:
Clientdns12.java
/*... datagram socket is the sending or receiving point for a packet delivery service.
DatagramSocket client=new DatagramSocket();
38
/*...InetAddress class provides methods to get the IP of any host name...*/
InetAddress addr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the
DOMAIN NAME or IP adress:");
String str=in.readLine(); sendbyte=str.getBytes();
/*…send the data to the server(data,length,ip address and port number)…*/ DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,1309); client.send(sender);
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new String(receiver.getData());
System.out.println("IP address or DOMAIN NAME: "+s.trim());
Serverdns12.java
DatagramSocket server=new DatagramSocket(1309);
while(true)
{byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
/*..receiving the packet from client…*/
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData()); String
s=str.trim();
//System.out.println(s);
InetAddressaddr=receiver.getAddress(); int
port=receiver.getPort();
Sample Output:
APPLICATIONS (SNMP)
Concept:
Sample Code:
publicSNMPManager(String add)
{address = add;
public static void main(String[] args) throws IOException {
/*...Port 161 is used for Read and Other operations, Port 162 is used for the trap
generation ...*/
SNMPManager client = new SNMPManager("udp:127.0.0.1/161");
client.start();
/*...Method which takes a single OID and returns the response from the agent as a
String...*/
public String getAsString(OID oid) throws IOException { ResponseEvent
event = get(new OID[]{oid}); returnevent.getResponse().get(0).get
Variable().toString();}
41
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null); if(event != null) { return event;}
throw new RuntimeException("GET timed out");}
/*... This method returns a Target, which contains information about where the
data should be
fetched and how to return ...*/
private Target getTarget() {
Address targetAddress = GenericAddress.parse(address); CommunityTarget target
= new CommunityTarget();
target.setCommunity(new OctetString("public")); target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c); return target;}}
Sample Output:
Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE – Software:
42
EXPERIMENT NO. -10
AIM: Study of Network simulator (NS).and Simulation of CO1, PO1, PO2, PO3,
Congestion Control Algorithms using NS PO4, PO5, PO11, PO12
Objective:
This lab session we Study the Network simulator (NS) and Simulation of Congestion Control Algorithms using NS.
Tasks:
Ns Functionalities
Routing, Transportation, Traffic sources,queuing disciplines, QoS
Wireless
Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various utilitiesNS(Network Simulators)
Most of the commercial simulators are GUI driven, while some network simulators are CLI driven. The
network model / configuration describe the state of the network (nodes, routers, switchesand links) and the
events (data transmissions, packet error etc.). The 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 variants"
and "importance sampling" have been developed to speed simulation.
Examples of network simulators
43
There are many both free/open-source and proprietary network simulators. Examples of notable network
simulation software are, ordered after how often they are mentioned in research papers:
ns (open source)
OPNET (proprietary software)
NetSim (proprietary software)
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 the network. Network simulators are particularly useful in allowing
researchers to test new networking protocols or changes to existing protocols in a controlled and reproducible
environment. 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 various types of nodes like
computers, hubs, bridges, routers, switches, links, mobile units etc. 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 a typical simulator and the user can test, analyse various standard
results apart from devising some novel protocol or strategy for routing etc. Network simulators are also
widely used to simulate battlefield 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.
Packet loss 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 it is for transport layer protocols to maintain high
bandwidths, the sensitivity to loss of individual packets, as well as to frequency and patterns of loss among
longer packet sequences is strongly dependent on the application itself.
Throughput
This 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. The throughput is usually measured in bit sper second
(bit/s orbps), and sometimes in data packet sper second or data packets per time slot This measure how
soon the receiver is able to get a certain amount of data send by the sender. It is determined as the ratio of
44
the total data received to the end to end delay. Throughput is an important factor which directly impacts
the 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 valueof delay, the more difficult it is for transport
layer protocols to maintain high bandwidths. We will calculate end to end 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.
45
EXPERIMENT NO. –11
AIM: Perform a case study about the different routing algorithms CO1, PO1, PO2, PO3,
to select the network path with its optimum and economical PO4, PO5, PO11, PO12
during data transfer. i. Link State routing ii. Flooding iii.
Distance vector
Objective:
This lab session we Perform a case study about the different routing algorithms to select the network path with its
optimum and economical during data transfer.
i. Link State routing
ii. ii. Flooding
iii. iii. Distance vector
Tasks:
3. Administrative distance: where a lower distance is preferred (only valid between different routing
protocols) Routing, in a more narrow sense of the term, is often contrasted with bridging in its assumption
that network addresses are structured and that similar addresses imply proximity within the network.
Structured addresses allow a single routing table entry to represent the route to a group of devices. In large
networks, structured addressing (routing, in the narrow sense) outperforms unstructured addressing
(bridging). Routing has become the dominant form of addressing on the Internet. Bridging is still widely
used within localized environments.
46
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 fatal law of flooding. All nodes have neighbors and route
packets indefinitely. More than two neighbors create a broadcast storm. Controlled Flooding has its own
two algorithms to make it reliable, SNCF (Sequence Number Controlled Flooding) and RPF (Reverse
Path Flooding). In SNCF, the node attaches its own address and sequence number to the packet, since every
node has a memory of addresses and sequence numbers. If it receives a packet in memory, it drops it
immediately while in RPF, the node will only send the packet forward. If it is received from the next node,
it sends it back to the sender.
Algorithm
There are several variants of flooding algorithm. Most work roughly as follows:
1. Each node acts as both a transmitter and a receiver.
2. Each node tries to forward every message to every one of its neighbours except the source node. This
results in every message eventually being delivered to all reachable parts of the network. Algorithms may
need to be more complex than this, since, in some case, precautions have to be taken to avoid wasted
duplicate deliveries and infinite loops, and to allow messages to eventually expire from the system. A
variant of flooding called selective flooding partially addresses these issues by only sending packets to routers
in the same direction. In selective flooding the routers don't send every incoming packet on every line but
only on those lines which are going approximately in the right direction.
Advantages
• packet can be delivered, it will (probably multiple times).
• Since flooding naturally utilizes every path through the network, it will also use the shortest path.
• This algorithm is very simple to implement.
Disadvantages
Flooding can be costly in terms of wasted bandwidth. While a message may only have one destination it has
to be sent to every host. In the case of a ping flood or a denial of service attack, it can be harmful to the
reliability of a computer network. Messages can become duplicated in the network further increasing the load
on the networks bandwidth as well as requiring an increase in processing complexity to disregard duplicate
messages. Duplicate packets may circulate forever, unless certain precautions are taken: Use a hop count or
a time to live count and include it with each packet. This value should take into account the number of nodes
that a packet may have to pass through on the way to its destination.
Distance-vector protocols are based on calculating the direction and distance to any link in a network.
"Direction" usually means the next hop address and the exit interface. "Distance" is a measure of the cost
to reach a certain node. The least cost route between any two nodes is the route with minimum distance. Each
node maintains a vector (table) of minimum distance to every node. The cost of reaching a destination is
calculated using 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 a router's routing table is sent to all its neighbors that are
configured to use the same distance-vector routing protocol. RIP supports cross-platform distance vector
routing whereas IGRP is a Cisco Systems proprietary distance vector routing protocol. Once a router has
this information it is able to amend its own routing table to reflect the changes and then inform its neighbors
of the changes. This process has been described as routing by rumor‘ because routers are relying on the
information they receive from other routers and cannot determine if the information is actually valid and
true. There are a number of features which can be used to help with instability and inaccurate routing
information.
EGP and BGP are not pure distance-vector routing protocols because a distance-vector protocol calculates
routes based only on link costs whereas in BGP, for example, the local route preference value takes priority
over the link cost.
Count-to-infinity problem
The Bellman–Ford algorithm does not prevent routing loops from happening and suffers from the count to
infinity problem. The core of the count-to-infinity problem is that if A tells B that it has a path somewhere,
there is no way for B to know if the path has B as a part of it. To see the problem clearly, imagine a subnet
connected like A–B–C–D–E–F, and let the metric between the routers be "number of jumps". Now suppose
that A is taken offline. In the vector-update-process B notices that the route to A, which was distance 1, is
down – B does not receive the vector update from A. The problem is, B also gets an update from C, and C
is still not aware of the fact that A is down – so it tells B that A is only two jumps from C (C to B to A),
which is false. This slowly propagates through the network until it reaches infinity (in which case the
algorithm corrects itself, due to the relaxation property of Bellman–Ford).
48
EXPERIMENT NO. – 12
AIM: To learn handling and configuration of networking CO1, PO1, PO2, PO3,
hardware like RJ-45 connector, CAT-6 cable, crimping PO4, PO5, PO11, PO12
tool etc.
Standard Cabling:
1. 10BaseT and 100BaseT are most common mode of LAN. You can use UTP category-5 cable for both
modes.
2. A straight cable is used to connect a computer to a hub
49
CROSSOVER CABLES - The purpose of a Crossover Ethernet cable is to directly connect one computer to
another computer (or device) without going through a router, switch or hub.
50
Bulk RJ45 Crimpable Connectors for CAT-6
phone
51
IO connector crimping: Run the full length of Ethernet cable in place, from
endpoint to endpoint, making sure to leave excess.
At one end, cut the wire to length leaving enough length to work, but not too much excess.
Strip off about 2 inches of the Ethernet cable sheath.
Align each of the colored wires according to the layout of the jack.
Use the punch down tool to insert each wire into the jack.
Repeat the above steps for the second RJ45 jack.
52
Result:
Cable Crimping, Standard Cabling and Cross Cabling, IO connector crimping and testing the crimped cable
using a cable tester are done successfully
53
EXPERIMENT NO. – 13
AIM: Configuration of router, hub, switch etc. (using real CO1, PO1, PO2, PO3,
devices or simulators) PO4, PO5, PO11, PO12
Objective:
Following should be done to understand this practical.
Tasks:
1. Repeater: Functioning at Physical Layer. A Repeater is an electronic device that receives a signal and
retransmits it at a higher level and/or higher power, or onto the other side of an obstruction, so that the signal can
cover longer distances. Repeater have two ports ,so cannot be use to connect for more than two devices
2. Hub: An Ethernet hub, active hub, network hub, repeater hub, hub or concentrator
is a device for connecting multiple twisted pair or fiber optic Ethernet devices together and making them act as a
single network segment. Hubs work at the physical layer (layer 1) of the OSI model. The device is a form of
multiport repeater. Repeater hubs also participate in collision detection, forwarding a jam signal to all ports if it
detects a collision.
3. Switch: A network switch or switching hub is a computer networking device that connects network
segments. The term commonly refers to a network bridge that processes and routes data at the data link layer
(layer 2) of the OSI model. Switches that additionally process data at the network layer (layer 3 and above) are
often referred to as Layer 3 switches or multilayer switches.
4. Bridge: A network bridge connects multiple network segments at the data link layer (Layer 2) of the
OSI model. In Ethernet networks, the term bridge formally means a device that behaves according to the IEEE
802.1D standard. A bridge and switch are very much alike; a switch being a bridge with numerous ports. Switch
or Layer 2 switch is often used interchangeably with bridge .Bridges can analyze incoming data packets to
determine if the bridge is able to send the given packet to another segment of the network.
5. Router: A router is an electronic device that interconnects two or more computer networks, and
selectively interchanges packets of data between them. Each data packet contains address information that a
router can use to determine if the source and destination are on the same network, or if the data packet must be
transferred from one network to another. Where multiple routers are used in a large collection of interconnected
networks, the routers exchange information about target system addresses, so that each router can build up a table
showing the preferred paths between any two systems on the interconnected networks.
6. Gate Way: In a communications network, a network node equipped for interfacing with another
network that uses different protocols.
• A gateway may contain devices such as protocol translators, impedance matching devices, rate converters,
fault isolators, or signal translators as necessary to provide system interoperability. It also requires the
establishment of mutually acceptable administrative procedures between both networks.
• A protocol translation/mapping gateway interconnects networks with different network protocol
technologies by performing the required protocol conversions.
54
55
EXPERIMENT NO. –14
AIM: Running and using services/commands like ping, CO1, PO1, PO2, PO3,
traceroute, arp, telnet, etc. PO4, PO5, PO11, PO12
Objective:
This lab session we study the Running and using services/commands like ping, traceroute, arp, telnet, etc
Tasks:
Tracert / traceroute
Tracert: Determines the path taken to a destination by sending Internet Control Message Protocol (ICMP) Echo
Request messages to the destination with incrementally increasing Time to Live (TTL) field values. The path
displayed is the list of near-side router interfaces of the routers in the path between a source host and a destination.
The near-side interface is the interface of the router that is closest to the sending host in the path. Used without
parameters, tracert displays help.
This diagnostic tool determines the path taken to a destination by sending ICMP Echo Request messages with
varying Time to Live (TTL) values to the destination. Each router along the path is required to decrement the
TTL in an IP packet by at least 1 before forwarding it.
Effectively, the TTL is a maximum link counter. When the TTL on a packet reaches 0, the router is expected to
return an ICMP Time Exceeded message to the source computer. Tracert determines the path by sending the first
Echo Request message with a TTL of 1 and incrementing the TTL by 1 on each subsequent transmission until
the target responds or the maximum number of hops is reached. The maximum number of hops is 30 by default
and can be specified using the -h parameter.
The path is determined by examining the ICMP Time Exceeded messages returned by intermediate routers and
the Echo Reply message returned by the destination. However, some routers do not return Time Exceeded
messages for packets with expired TTL values and are invisible to the tracert command. In this case, a row of
asterisks (*) is displayed for that hop.
Examples:
To trace the path to the host named www.google.co.in use following command
tracert www.google.co.in
To trace the path to the host named www.google.com and prevent the resolution of each IP address
to its name, type:
tracert -d www.google.com
To trace the path to the host named www.google.com and use the loose source route 10.12.0.1-
10.29.3.1-10.1.44.1, type:
tracert -j 10.12.0.1 10.29.3.1 10.1.44.1 www.google.com
56
Syntax
Parameters
-d Prevents tracert from attempting to resolve the IP addresses of intermediate routers to their names.
This can speed up the display of tracert results.
-h MaximumHops Specifies the maximum number of hops in the path to search for the target (destination).
The default is 30 hops.
-j HostList Specifies that Echo Request messages use the Loose Source Route option in the IP header with
the set of intermediate destinations specified in HostList. With loose source routing, successive
intermediate destinations can be separated by one or multiple routers. The maximum number of addresses
or names in the host list is 9. The HostList is a series of IP addresses (in dotted decimal notation) separated
by spaces.
-w Timeout Specifies the amount of time in milliseconds to wait for the ICMP Time Exceeded or Echo
Reply message corresponding to a given Echo Request message to be received. If not received within
the time-out, an asterisk (*) is displayed. The default time-out is 4000 (4 seconds).
Ping
Verifies IP-level connectivity to another TCP/IP computer by sending Internet Control Message Protocol (ICMP)
Echo Request messages. The receipt of corresponding Echo Reply messages are displayed, along with round-trip
times. Ping is the primary TCP/IP command used to troubleshoot connectivity, reachability, and name resolution.
57
You can use ping to test both the computer name and the IP address of the computer. If pinging the IP address
is successful, but pinging the computer name is not, you might have a name resolution problem. In this case,
ensure that the computer name you are specifying can be resolved through the local Hosts file, by using
Domain Name System (DNS) queries, or through NetBIOS name resolution techniques.
➢ To quickly obtain the TCP/IP configuration of a computer, open Command Prompt, and then
type ipconfig . From the display of the ipconfig command, ensure that the network adapter for the
TCP/IP configuration you are testing is not in a Media disconnected state.
➢ At the command prompt, ping the loopback address by typing ping 127.0.0.1
➢ Ping the IP address of the computer.
➢ Ping the IP address of the default gateway. If the ping command fails, verify that the default gateway IP
address is correct and that the gateway (router) is operational.
➢ Ping the IP address of a remote host (a host that is on a different subnet). If the ping command fails,
verify that the remote host IP address is correct, that the remote host is operational, and that all of the
gateways (routers) between this computer and the remote host are operational.
➢ Ping the IP address of the DNS server. If the ping command fails, verify that the DNS server IP address
is correct, that the DNS server is operational, and that all of the gateways (routers) between this
computer and the DNS server are operational.
ARP
Displays and modifies entries in the Address Resolution Protocol (ARP) cache, which contains one or more tables
that are used to store IP addresses and their resolved Ethernet or Token Ring physical addresses. There is a
separate table for each Ethernet or Token Ring network adapter installed on your computer.
Syntax
arp [-a [InetAddr] [-N IfaceAddr]] [-g [InetAddr] [-N IfaceAddr]] [-d InetAddr [IfaceAddr]]
[-s InetAddr EtherAddr [IfaceAddr]]
58
Parameters
Examples:
To display the ARP cache tables for all interfaces use following command
arp -a
59
To display the ARP cache table for the interface that is assigned the IP address 192.168.42.171
TELNET
The telnet command is used for connection and communication with a remote or local host via the Telnet
TCP/IP protocol.
You can enter a domain or IP address and try connecting to it via the chosen port. In case the port is not
specified, telnet utility tries to connect via the default port 23.
The command is really useful in cases when you need to check whether the needed port is open on your
computer and on the side of the remote host.
How to use Telnet
For Windows
60
2. Go to the Programs section:
4. Scroll down the list available in the Windows Features window > check Telnet Client option >
press OK > wait a few moments for the changes to be applied
61
5. Telnet is enabled now, so we can run it in the same way as other commands:
for example:
telnet namecheap.com 80
If you see the blank output after that, you have connected successfully. To quit you can press CTRL + C or any
key:
As a result of successful telnet, we can conclude, that the entered domain or IP exists, and the chosen port is
62
open on your computer and on the side of the target host.
If connection has not been established, the following error will appear:
63
EXPERIMENT NO. –15
AIM: Network packet analysis using tools like Wireshark, CO1, PO1, PO2, PO3,
tcpdump, etc. PO4, PO5, PO11, PO12
Objective:
This lab session we study the Running and using services/commands like ping, traceroute, arp, telnet, etc
Tasks:
tcpdump
The fundamental tool of almost all network traffic collection is tcpdump. It is an open-source application that
comes installed on almost all Unix-like operating systems. Tcpdump is an excellent collection tool and comes
complete with a very complex filtering language. It’s essential to know how to filter the data at collection time
to end up with a manageable chunk of data to analyze. Capturing all data from a network device on even a
moderately busy network can create too much data to analyze efficiently.
In some rare cases, allowing tcpdump to output its capture directly to your screen may be enough to find what
you’re looking for. For example, in writing this article, captured some traffic and noticed that machine was
sending traffic to an IP address . It turns out that machine was sending data to a Google IP address of
172.217.11.142.
It seems that even when Chrome is not running in the foreground it remains running as a service. it would not
have necessarily noticed this without a packet analysis to tip me off. it re-captured some more tcpdump data but
this time told tcpdump to write the data to a file that itopened in Wireshark (more on that later). Here’s that
entry:
Tcpdump is a favorite tool among sysadmins because it is a command-line tool. This means that it doesn’t
require a full-blown desktop to run. It is unusual for production servers to provide a desktop because of the
resources that would take, so command-line tools are preferred. As with many advanced tools, tcpdump has a
very rich and arcane language that takes some time to master.
64
Key Features:
A few of the very basic commands involve selecting the network interface from which to collect data, and
writing that data to a file so it can be exported for analysis elsewhere. The -i and -w switches are used for this.
file tcpdump_packets
tcpdump_packets: tcpdump capture file (little-endian) - version 2.4 (Ethernet, capture length 262144)
The standard TCP capture file is a pcap file. It is not text so it can only be read by an analysis program that
knows how to read pcap files.
Wireshark
Wireshark is probably the next best-known tool in any sysadmin’s toolkit. It can not only capture data, but also
provides some advanced analysis tools. Adding to its appeal, Wireshark is open source, and has been ported over
to almost every server operating system that exists. Starting life named Ethereal, Wireshark now runs everywhere,
including as a standalone portable app.
If you’re analyzing traffic on a server with a desktop installed, Wireshark can do it all for you. The collected
packets can then be analyzed all in one spot. However, desktops are not common on servers, so in many cases,
you’ll want to capture the network data packets remotely and then pull the resulting pcap file into Wireshark.
At first launch, Wireshark allows you to either load an existing pcap file, or start capturing. If you elect to capture
network traffic, you can optionally specify filters to pare down the amount of data Wireshark collects. Since its
analysis tools are so good, it’s less important to ensure you surgically identify the data at collection time with
Wireshark. If you don’t specify a filter, Wireshark will simply collect all network data that your selected interface
observes.
65
One of the most useful tools Wireshark provides is the ability to follow a stream. It’s probably most useful to
think of a stream as an entire conversation. In the screenshot below we can see a lot of data has been captured,
but what is most interested in is that Google IP address. itcan right-click it and Follow the TCP Stream to see the
entire conversation.
If you’ve captured traffic elsewhere, you can import the pcap file using Wireshark’s File -> Open dialogue. The
same filters and tools that can be used for natively captured network data are available for imported files.
66
67
EXPERIMENT NO. – 16
AIM: Network simulation using tools like Cisco Packet Tracer, CO1, PO1, PO2, PO3,
NetSim, OMNeT++, NS2, NS3, etc. PO4, PO5, PO11, PO12
Objective:
Student should understand Network simulation using tools like Cisco Packet Tracer, NetSim, OMNeT++, NS2, NS3 in
this practical.
Tasks:
Simulation is a very important technology in modern time. Computer assisted simulation can model
hypothetical and real-life objects or activities on a computer to study the well-designed structure. A network
simulator is a system of implementing the network on the computer through which the performance of the
network is calculated. The computer assisted simulation technologies are applied in the simulation of
networking algorithms. The functional network field is narrower than general simulation and it is natural that
more specific requirements will be placed on network simulations.
Network simulator allows the researchers to test the scenarios that are difficult or expensive to simulate
in real world. Design of various network topologies using nodes, hosts, hubs, bridges, routers and mobile units
etc. is possible. The network simulators are of various types which can be compared on the basis of: range
(simple to the complex), specification of nodes, links and traffic between the nodes. Specifying about the
protocols used to handle traffic in a network, user friendly applications (allow users to easily visualize the
simulated environment.), text-based applications (permit more advanced forms of customization) and
programming-oriented tools (providing a programming framework that customizes to create an application
that simulates the networking environment to be tested).
Network simulators are used by people from different areas such as academic researchers,
industrialized sectors and Quality Assurance (QA) to design, simulate and analyze the performance of different
network protocols. They can also be used to evaluate the outcome of the different parameters of the protocols
being studied. Normally a network simulator comprises of wide range of networking technologies and protocols
that help users to build complex networks from basic building blocks like clusters of nodes and links. With
their help, different network topologies can be designed using various types of nodes such as end-hosts,
network bridges, routers, hubs, optical link-layer devices and mobile units.
Generally, network simulators try to represent the real world networks and it is a useful technique, given that
the activities of a network can be modeled by calculating the interaction between the different network
components (they can be end-host or network entities such as routers, packets or physical links) using
mathematical formulas. They can also be modeled by actually or virtually capturing and playing back
experimental observations from real networks. Upon receipt of the observation data from simulation
experiments, the behavior of the network and protocols supported are analyzed in a series of offline test
experiments. All types of attributes can also be modified in a controlled manner to assess how the network can
68
behave under different parameter combinations. Another feature of network simulation worth noticing is that
the simulation program can be used and analyzed together with various strategy, links, applications etc.
Typically, users can then adapt the simulator to fulfill their exact needs. Simulators support the most popular
protocols and networks such as WLAN, TCP and WSN.
Simulators
Most of the commercial simulators are Graphical User Interface (GUI) driven, while some network
simulators are Command-Line Interface (CLI). The design of the network describes the state of the network
(nodes, routers, switches and links) and the events (data transfer, transmission delay, packet error etc.). The
major output of simulation is the trace files which log every packet and event that occurred during simulation
and is used for analysis. Also provides other tools to facilitate visual analysis of trends and potential trouble
spots. Most of the network simulators are discrete event, in which the list of pending "events" are stored and
processed in order. Some events triggers the future events (i.e.) 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 difficult task. For example, if blocking is high, then evaluation of the
average occupancy is challenging because of high variance. To evaluate the probability of buffer overflow in
a network, the time required for a precise answer can be enormously large. Techniques like "control variants"
and “sampling" have been developed to speed simulation.
A typical simulator encompasses a wide range of networking technologies and can help the users to
build complex networks from basic building blocks such as selection of nodes and links. Various types of
nodes in Hierarchical networks resembling computers, hubs, bridges, routers, links, switches mobile units etc
can be designed with the help of simulators.
69
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 be imitated with a simulator and the user can
examine various standard results apart from devising some novel protocol or routing strategy. Network
simulators are widely used to simulate battlefield networks in Network-centric warfare.
There are ample varieties of simulators, ranging from simple to complex. A simple simulator must
enable a user to represent network topology, to specify nodes on the network, the links and the traffic between
the nodes. More complex systems may permit the user to specify everything about the protocols used to handle
traffic in a network. User friendly applications permit users to envision easily the working mechanism of their
simulated situation. Text-based applications offer a less sensitive interface, but permits more advanced forms
of customization.
Overview of Network Simulators
Currently there are many network simulators that have different features in different aspects. Short
lists of the current network simulators include NS-2, NS-3, OPNET, OMNeT++, NETSIM, QualNet, and J-
Sim. These network simulators are selected for discussion regarding their features, advantages and restrictions.
NS2
The Ns2 is a discrete event simulator targeted at packet level networking research and provides
substantial support to simulate group of protocols like TCP, UDP, FTP and HTTP. It comprises of two
simulation tools. Ns-2 is primarily UNIX based and fully simulates a layered wire or wireless network from
the physical radio transmission channel to high-level applications. The simulator is written in C++ and a script
language called OTcl.
C++: C++ is fast to run but slower to change, making it suitable for detailed protocol implementation.
Otcl: OTcl runs much slower but can be changed very quickly (and interactively), making it ideal for
simulation configuration. Ns provides glue to make objects and variables appear on both languages.
NS2 uses an OTcl interpreter by which the user writes an OTcl script that defines the network, (number
of nodes and links) the transaction in the network (sources destinations, type of traffic) and the type of protocols
used. The outcome of the simulation is a trace file that can be used for data processing (calculate delay,
throughput etc). To visualize the simulation, a program called Network Animator (NAM) is used. It visualizes
the packets as they propagate throughout the network. The ns- 2 simulator has numerous features that make it
suitable for our simulations.
70
Advantages:
1. NS2 has large number of available models, realistic mobility models, powerful and flexible
scripting and simulation setup, large user community and ongoing development.
2. NS2 provides an easy traffic and movement pattern by including an efficient energy model.
3. It provides a set of randomized mobility model and there are several projects to bring advanced
mobility models to the simulators.
4. Complex scenarios can be easily tested.
5. Popular for its modularity.
Limitations:
1. NS2 needs to be recompilation every time if there is a change in the user code.
2. Real system is too complex to model i.e. complicated infrastructure.
NS3
The ns-3 simulator is a discrete-event network simulator for Internet systems, targeted primarily for
research and learning purpose. The ns-3 project, started in 2006, is open-source free software, licensed under
the GNU GPLv2 license. It will rely on the current contributions of the community to develop new models,
debug or maintain the existing ones, and share the results. Ns3 is mainly used on LINUX systems and not
limited to internet based systems alone.
C++: implementation of simulation and core model.Ns-3 is built as a library which may be statically or
dynamically linked to a C++ main program. These libraries describe the beginning of simulation and their
topology.
Python: C++ wrapped by Python. Python programs to import an “ns3” module. The features of NS3 simulator
are given below.
Advantages:
1. High modularity than its ancestor NS2.
2. Support simulation for TCP, UDP, ICMP, IPv4, multicast routing, P2P and CSMA protocols.
3. Support for ported code should make model validation easier and more credible.
4. Much more flexible than any other simulators.
5. Wide range of use in both optimization and expansion of the existing networks.
Limitations:
71
1. NS3 still suffers from lack of credibility.
2. NS3 is intended to replicate the successful mode of NS2 in which various organizations contributed
to the models and components based on the framework of NS2.
3. NS3 needs a lot of specialized maintainers in order to avail the merits of NS3 as the commercial
OPNET network simulators.
4. Active maintainers are required to respond to the user questions, bug reports and help to Test &
validate the system.
OMNET++
It is a component-based, modular and open architecture discrete event simulator framework. The most
common use of OMNeT++ is for simulation of networks, but it is also used for queuing network simulations
and other areas as well. It is licensed under its own Academic Public License, which permits GNU Public
License like freedom but only in noncommercial settings. It provides component architecture for models.
C++: The C++ class library comprises of simulation kernel and utility classes (for random number
generation, statistics collection, topology discovery etc) -- this one is used to create simulation components
(simple modules and channels); infrastructure to assemble simulations from these components and configure
(NED language, ini files); runtime user interfaces or environments for simulations (Tkenv, Cmdenv); an
Eclipse-based simulation IDE for designing, running and evaluating simulations; extension interfaces for real-
time simulation, emulation, MRIP, parallel distributed simulation, database connectivity and so on.
The OMNeT++ components include:
NETSIM
72
NetSim is a discrete event simulator developed by Tetcos in 1997, in association with Indian Institute
of Science. It has also been featured with Computer Networks and Internets V edition by Dr. Douglas Comer,
published by Prentice Hall. It has an object-oriented system simulating environment to support simulation and
analysis of voice and data communication scenarios for High Frequency Global Communication Systems
(HFGCS).
Java: It creating fast, platform independent software that could be used in simple, consumer electronic
products. Java designed for simple, efficient, platform-independent program for creating WWW-based
programs. Using Java one can create small programs called applets that are entrenched into an HTML
document and viewable on any Java-compatible browser. Java applets are compiled into a set of byte-codes,
or machine-independent processing instructions.
Features:
• NetSim modeling and simulation are supported for Aloha, Slotted Aloha, Token Ring/Bus, Ethernet
CSMA/CD, Fast Ethernet, WLAN - IEEE 802.11 a/b/g/n and e, X.25, Frame Relay, TCP, UDP, IPv4
and IPv6, Routing - RIP, OSPF, BGP,MPLS, MANET, GSM, CDMA, Wire-less Sensor Network,
Zigbee, Cognitive radio)[5].
• It simulates a wide variety of Cisco routers, including 2500 series, 2600 series, 2800 series, and 3600
series, as well as the Cisco Catalyst 1900 series, 2900 series, and 3500 series switches. Protocol libraries
are available as open C code for user modification. This can help to avoid the time consuming process
such as encoding, customization and configuring commercial simulators to meet customer specific
needs. Along with the Boson Virtual Packet Technology engine NetSim utilizes Boson’s proprietary
Router & Simulator EROUTER software technologies, to produce individual packets. These packets
are routed and switched through the simulated network, allowing the simulator to build an appropriate
virtual routing table and simulate proper networking. Other simulation products on the market do not
support this level of functionality.
• It can be used to create a simulation of the topology of corporate network and help practice trouble-
shooting without using devices on the production network.
Advantages:
1. NetSim has a GUI which features drag and drop functionality for devices, links etc. i.e. Modeling
in NetSim is simple and user friendly.
2. It has a built in analysis framework that provides intra and inter-protocol performance comparison
with graphical options.
3. Data packet and control packet flow can be visual-ized through NetSim built-in packet animator.
4. It is easy to learn all about NetSim.
Limitations:
1. NetSim is a single process discrete event simulator. A single event queue is used for the simulation
which at any given time contains one entry for each station on the network.
2. Free version of NetSim is not available.
73
Cisco Packet Tracer
Cisco Packet Tracer is a powerful network simulation program that allows students to experiment with network
behavior and ask “what if” questions. As an integral part of the Networking Academy comprehensive learning
experience, Packet Tracer provides simulation, visualization, authoring, assessment, and collaboration
capabilities to facilitate the teaching and learning of complex technology concepts.
Packet Tracer supplements physical equipment in the classroom by allowing students to create a network with
an almost unlimited number of devices, encouraging practice, discovery, and troubleshooting. The simulation-
based learning environment helps students develop 21st century skills such as decision making, creative and
critical thinking, and problem solving. Packet Tracer complements the Networking Academy curricula,
allowing instructors to easily teach and demonstrate complex technical concepts and networking systems
design. Instructors can customize individual or multiuser activities, providing hands-on lessons for students
that offer value and relevance in their classrooms. Students can build, configure, and troubleshoot networks
using virtual equipment and simulated connections, alone or in collaboration with other students. Packet Tracer
offers an effective, interactive environment for learning networking concepts and protocols. Most importantly,
Packet Tracer helps students and instructors create their own virtual “network worlds” for exploration,
experimentation, and explanation of networking concepts and technologies.
Packet Tracer’s drag-and-drop interface allows students to configure and validate system architecture
Cisco Packet Tracer has two workspaces—logical and physical. The logical workspace allows users to build
logical network topologies by placing, connecting, and clustering virtual network devices. The physical
74
workspace provides a graphical physical dimension of the logical network, giving a sense of scale and
placement in how network devices such as routers, switches, and hosts would look in a real environment. The
physical view also provides geographic representations of networks, including multiple cities, buildings, and
wiring closets.
Network • BGP, IPv4, ICMP, ARP, IPv6, ICMPv6, IPSec, RIPv1/ v2/ng, Multi-Area OSPF,
EIGRP, Static Routing, Route Redistribution, Multilayer Switching, L3 QoS, NAT, CBAL, ,
Zone-based policy firewall and Intrusion Protection,System on the ISR, GRE VPN, IPSec
VPN
Network Access/ • Ethernet (802.3), 802.11, HDLC, Frame Relay, PPP, PPPoE, STP, RSTP, VTP, DTP,
Interface CDP, 802.1q, PAgP, L2 QoS, SLARP, Simple WEP, WPA, EAP
75