CN LAB File
CN LAB File
Name __________________________________________
Roll No __________________________________________
Year __________________________________________
7. Implementation of Subnetting.
Normal operation
After transmitting one packet, the sender waits for an acknowledgment (ACK) from the
receiver before transmitting the next one. In this way, the sender can recognize that the previous
packet is transmitted successfully and we could say "stop-n-wait" guarantees reliable transfer
between nodes .To support this feature, the sender keeps a record of each packet it sends.
Also, to avoid confusion caused by delayed or duplicated ACKs,"stop wait"sends each packets
with unique sequence number sand receives that numbers in eachACKs.
1) Timeout
2)
If the sender doesn't receive ACK for previous sent packet after a certain period of time, the sender times out
and retransmit that packet again. There are two cases when the sender doesn't receive ACK; one is when the
ACK is lost and the other is when the frame itself is not transmitted.
To support this feature, the sender keeps timer per each packet.
PROGRAM
#include<stdio.h>
int sender();
int recv();
int timer=0,wait_for_ack=-1,frameQ=0,cansend=1,t=0;
main()
{
int i,j;
int frame[5];
printf("enter the time when data frame will be ready\n");
for(j=0;j<3;j++)
{
sender( i,frame[]);
recv(i);
}
sender(int i,int frame[])
{
wait_for_ack++;
if (wait_for_ack==3)
{
if(i==frame[t])
{
frameQ++;
t++;
}
if(frameQ==0)
printf("NO FRAME TO SEND at time=%d \n",i);
if(frameQ>0 &&cansend==1)
{
printf("FRAME SEND AT TIME=%d\n",i);
cansend=-1;
frameQ--;
timer++;
printf("timer in sender=%d\n",timer);
}
if(frameQ>0 &&cansend==-1)
printf("FRAME IN Q FOR TRANSMISSION AT TIME=%d\n",i);
if(frameQ>0)
t++;
}
printf("frameQ=%d\n",frameQ);
printf("i=%d t=%d\n",i,t);
printf("value in frame=%d\n",frame[t]);
return 0;
}
int recv(int i )
{
printf("timer in recvr=%d\n",timer);
if(timer>0)
{
timer++;
}
if(timer==3)
{
printf("FRAME ARRIVED AT TIME= %d\n",i);
wait_for_ack=0;
timer=0;
}
else
printf("WAITING FOR FRAME AT TIME %d\n",i);
return 0;
}
}
A socket is formally defined as an endpoint for communication between an application program, and the
underlying network protocols
• Connection-oriented service
• Connection less service
Programmer can choose a connection-oriented server or a connectionless server based on their applications.
In Internet Protocol terminology, the basic unit of data transfer is a datagram. This is basically a header
followed by some data. The datagram socket is connectionless.
1. Is a connectionless.
2. A single socket can send and receive packets from many different computers.
3. Best effort delivery.
4. Some packets may be lost some packets may arrive out of order.
1. Is a connection-oriented
2. A client must connect a socket to a server
3. TCP socket provides bidirectional channel between client and server.
4. Lost data is re-transmitted.
5. Data is delivered in-order.
6. Data is delivered as a stream of bytes.
7. TCP uses flow control.
1. Stream socket
2. Data gram socket
3. Raw socket
Stream socket: Stream socket are used for stream connections, means that exists for along duration. TCP
connection use stream connection.
Data gram socket: Datagram connection are used for short term connection
Raw socket :Raw sockets are used to access low level protocols directly, bypassing the high level Protocols.
Program/Pseudocode:// raw_sock.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/ip.h>
#include<sys/socket.h>
#include<arpa/inet.h>
int main() {
//Structs that contain source IPaddressesstruct sockaddr_insource_socket_address, dest_socket_address;
intpacket_size;
// Allocate string buffer to hold incoming packet data unsigned
char*buffer=(unsignedchar*)malloc(65536);
//Open the raw socketintsock=socket(PF_INET,SOCK_RAW,IPPROTO_TCP);if(sock== -1)
{
//socket creation failed, may be because of non-root privilegesp error("Failedtocreatesocket");
exit(1);
while(1){
// recvfromisusedto read datafrom asocket
packet_size = recvfrom(sock , buffer , 65536 , 0 , NULL, NULL);if(packet_size ==-
1)
{
printf("Failed to get packets\n");
return1;
}
struct iphdr *ip_packet = (struct iphdr*)buffer;memset(&source_socket_address, 0,
sizeof(source_socket_address));source_socket_address.sin_addr.s_addr = ip_packet-
>saddr;memset(&dest_socket_address,0,sizeof(dest_socket_address));
dest_socket_address.sin_addr.s_addr=ip_packet>daddr;printf("IncomingPacket:\n");
printf("PacketSize(bytes):%d\n",ntohs(ip_packet->tot_len));
printf("SourceAddress:%s\n",(char*)inet_ntoa(source_socket_address.sin_addr));
printf("DestinationAddress:%s\n",(char*)inet_ntoa(dest_socket_address.sin_addr));
printf("Identification:%d\n\n",ntohs(ip_packet->id));
}
return 0;
}
Experiment No: 3
OBJECTIVE: Write a code simulating ARP /RARP protocols.
Address Resolution Protocol (ARP) is a communication protocol used to find the MAC (Media Access
Control) address of a device from its IP address. This protocol is used when a device wants to communicate
with another device on a Local Area Network or Ethernet.
Reverse ARP (RARP) - It is a networking protocol used by the client system in a local area network (LAN)
to request its IPv4 address from the ARP gateway router table. A table is created by the network
administrator in the gateway-router that is used to find out the MAC address to the corresponding IP
address.
C Program:
arpserver.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#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 name:");
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("\nARP table at serverside is=\n%s",shmptr);
shmdt(shmptr);
}
arpclient.c
#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 ARPtable is:");
printf("%s",shmptr);
printf("\[Link]\[Link]\[Link]\n");
scanf("%d",&a);
switch(a)
{
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);
}
Experiment No: 4
Concept:
Trace route is one of the most common utilities built into most operating systems.
It is useful for diagnosing network connections. It shows the path of a packet
going from your host/computer through each of the individual routes that handle
the packet and time required for it to go from one router to another up to the final
host/destination.
The ping command is used to determine the ability of a user’s computer to reach a
destination computer.
Program/Pseudo code:
How to use trace route for Windows
Perform the following actions to run the tracert command:
1. Select the Start button>click on the Run option.
2. In the command line, type in cmd and press Enter.
3. Input:tracert*******You need to use the domain name, the server's name or
its IP insteadof*******.
4. Press Enter.
How to use ping for Windows
1. Select the Start button>click on the Run option.
2. In the command line ,type in cmd and press Enter.
3. After that, type in one of the following commands and press
4. Enter ping [Link]
Experiment No. 5
Objective: Create a socket for HTTP for web page upload and download.
Algorithm
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link]; import [Link]; import [Link];
import [Link]; import [Link];
public class Client
{
public static void main(String args[]) throws Exception{ Socket soc;BufferedImage img = null;
soc=new Socket("localhost",4000);
[Link]("Client is running. ");
try {
[Link]("Reading image from disk. ");
img = [Link](new File("digital_image_processing.jpg")); ByteArrayOutputStream baos = new
ByteArrayOutputStream();
[Link](img, "jpg", baos);
[Link]();
byte[] bytes = [Link](); [Link]();
[Link]("Sending image to server. ");
OutputStream out = [Link]();
DataOutputStream dos = new DataOutputStream(out);
[Link]([Link]);
[Link](bytes, 0, [Link]);
[Link]("Image sent to server. ");
[Link]();
[Link]();
}catch (Exception e) { [Link]("Exception: " + [Link]());
[Link]();
}
[Link]();
}
}
Server
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Server {
public static void main(String args[]) throws Exception{
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
[Link]("Server Waiting for image");
socket=[Link](); [Link]("Client connected.");
InputStream in = [Link](); DataInputStream dis = new DataInputStream(in);
int len = [Link]();
[Link]("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len];
[Link](data);
[Link]();
[Link]();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = [Link](ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
[Link](icon);
[Link](l);
[Link]();
[Link](true);
}
}
Output
When you run the client code, following output screen would appear on client side.
Experiment No: 6
Concept: Remote procedure calls can be made from any language. Remote Procedure Call (RPC) protocol
is generally used to communicate between processes on different workstations. However, RPC works just
as well for communication between different processes on the same workstation.
Program/Pseudo code:
i. Numbers: A central system authority administers the program number; which permits the
implementation of program. The first implementation of a program is usually version number1.
ii. Numbers: Most new protocols evolve into more efficient, stable, and mature protocols. As a program
evolves, a new version number (versparameter)is assigned. The version number identifies which
Version of the protocol the caller is using. The first implementation of a remote program is usually
Designated as version number1 (or a similar form).
iii. Numbers: The procedure number identifies the procedure to be called. The procedure number
is documented in each program's protocol specification. For example, a file service protocol
specification can list the read procedure as procedure 5 and the write procedure as procedure12.
iv. Programs: The RPC program numbers and protocol specifications of standard
RPC services are in the header files in the /usr/include/rpcsvc directory.
v. Using the Highest Layer of RPC: Programmers who write remote procedure calls can make the
Highest layer of RPC available to other users through a simple C language front-end routine
that entirely hides the networking.
vi. Using the Intermediate Layer of RPC: The intermediate layer RPC routines are used for most
applications. The intermediate layer is sometimes overlooked in programming due to its simplicity and
lack of flexibility. At this level, RPC does not allow time- out specifications, choice of transport, or
process control in case of errors.
vii. Using the Lowes Layer of RPC: For the higher layers, RPC takes care of many details
Automatically .However , the lowest layer of the RPC library allows the programmer to change the
default Values for these details.
Allocating Memory with XDR :XDR routines not only do input and output, they also do
memory allocation. Consider the following XDR routine, xdr_chararr1, which deals with a fixed
array of bytes with lengthS IZE.
viii. Starting RPC from theinetdDaemon:An RPC server can be started from the inetddaemon.
The only difference between using the inetddaemon and the usual code is that the service creation
routine is called.
ix. Compiling and Linking RPC Programs: RPC subroutines are part of the [Link].
Experiment No : 7
Concept:When a bigger network is divided into smaller networks, to maintain security, then that is
known as Subnetting. So, maintenance is easier for smaller networks. For example, if we consider a
class A address, the possible number of hosts is 224 for each network, it is obvious that it is difficult to
maintain such a huge number of hosts, but it would be quite easier to maintain if we divide the network
into small parts.
Uses of subnetting
1. Subnetting helps in organizing the network in an efficient way which helps in expanding the
technology for large firms and companies.
2. Subnetting is used for specific staffing structures to reduce traffic and maintain order and
efficiency.
3. Subnetting divides domains of the broadcast so that traffic is routed efficiently, which helps in
improving network performance.
ALGORITHM:
SERVER:
STEP 1: Start
STEP 2: Declare the variables for the socket
STEP 3: Specify the family, protocol, IP address and port number
STEP 4: Create a socket using socket() function
STEP 5: Bind the IP address and Port number
STEP 6: Listen and accept the client’s request for the connection
STEP 7: Read the client’s message
STEP 8: Display the client’s message
STEP 9: Close the socket
STEP 10: Stop
CLIENT:
STEP 1: Start
STEP 2: Declare the variables for the socket
STEP 3: Specify the family, protocol, IP address and port number
STEP 4: Create a socket using socket() function
STEP 5: Call the connect() function
STEP 6: Read the input message
STEP 7: Send the input message to the server
STEP 8: Display the server’s echo
STEP 9: Close the socket
STEP 10: Stop
SOURCE CODE:
SERVER:
#include<stdio.h>
#include<netinet/in.h>
#include<netdb.h>
#define SERV_TCP_PORT 5035
int main(int argc,char**argv)
{
int sockfd,newsockfd,clength;
struct sockaddr_in serv_addr,cli_addr;
char buffer[4096];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=INADDR_ANY;
serv_addr.sin_port=htons(SERV_TCP_PORT);
printf("\nStart");
bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
printf("\nListening...");
printf("\n");
listen(sockfd,5);
clength=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clength);
printf("\nAccepted");
printf("\n");
read(newsockfd,buffer,4096);
printf("\nClient message:%s",buffer);
write(newsockfd,buffer,4096);
printf("\n");
close(sockfd);
return 0;
}
CLIENT:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define SERV_TCP_PORT 5035
int main(int argc,char*argv[])
{
int sockfd;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4096];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("[Link]");
serv_addr.sin_port=htons(SERV_TCP_PORT);
printf("\nReady for sending...");
connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
printf("\nEnter the message to send\n");
printf("\nClient: ");
fgets(buffer,4096,stdin);
write(sockfd,buffer,4096);
printf("Serverecho:%s",buffer);
printf("\n");
close(sockfd);
return 0;
}
OUTPUT:
SERVER:
CLIENT:
RESULT: Thus the program for TCP echo client server was executed and the output was
verified.
Experiment No : 9
Objective: Applications using TCP and UDP Sockets like DNS, SNMP and File Transfer
To write a java program for DNS application
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
/ UDP DNS Server Udp dns [Link]
import [Link].*;
import [Link].*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = [Link]();
for (int i=0; i < [Link]; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
OUTPUT
Server
javac [Link]
java udpdnsserver
Press Ctrl + C to Quit Request for host [Link]
Request for host [Link]
Request for host [Link]
Client
javac [Link]
java udpdnsclient
Enter the hostname : [Link]
IP Address: [Link]
java udpdnsclient
Enter the hostname : [Link]
IP Address: [Link]
java udpdnsclient
Enter the hostname : [Link]
Experiment No: 10
Objective: Study of Network simulator (NS) and Simulation of Congestion Control Algorithms
using NS.
Ns2 Program for congestion control: Congestion refers to a network state where a node or link carries
so much data that it may deteriorate network service quality, resulting in queuing delay, frame or data
packet loss and the blocking of new connections.
So, the data packet will be sent from the second path i.e. Router-1 --> Router-3 --> Router-2.
The Link State Routing Algorithm is an interior protocol used by every router to share information or
knowledge about the rest of the routers on the network. The link state routing algorithm is distributed by
which every router computes its routing table.
With the knowledge of the network topology, a router can make its routing table. Now, for developing
the routing table, a router uses a shortest path computation algorithm like Dijkstra's algorithm along with
the knowledge of the topology. The routing table created by each router is exchanged with the rest of the
routers present in the network, which helps in faster and more reliable delivery of data.
A router does not send its entire routing table with the rest of the routers in the inter-network. It only
sends the information of its neighbors. A router broadcasts this information and contains information
about all of its directly connected routers and the connection cost.
Now, the process of transferring the information about a router's neighbors is termed flooding. A router
transfers the information to all the inter-network routers except its neighbors. Every router that receives
the information sends the information copies to all its neighbors. In this way, all the routers of the inter-
connected network have the same copy of the information.
This information exchange only occurs when there is a change in the information. Hence, the link state
routing algorithm is effective.
A distance-vector routing (DVR) protocol requires that a router inform its neighbors of topology
changes periodically. Historically known as the old ARPANET routing algorithm (or known as
Bellman-Ford algorithm).
Bellman Ford Basics – Each router maintains a Distance Vector table containing the distance
between itself and ALL possible destination nodes. Distances, based on a chosen metric, are
computed using information from the neighbors’ distance vectors .
Experiment No : 12
Objective: To learn handling and configuration of networking hardware like RJ-45 connector,
CAT-6 cable, crimping tool, etc.
Concept: An 8-pin/8-position plug or jack is commonly used to connect computers onto Ethernet-
based local area networks (LAN).Ethernet data cable, is a4 twisted pairs heated copper wire cable that
Can support data transfer rates of upto1gigabits(1,000megabits).This higher band width allows for
quick transfer of large files in an office network.
A crimping tool is the tool used to deform the material and create the connection. Crimping is
commonly used in electrical work ,to attach wires together or wire to other connectors.
Program/Pseudo code:
1. Start by stripping off about 2 inches of the plastic jacket off the end of the cable. Be
very careful at this point, as to not nick or cut into the wires, which are inside. Doing so
could alter the characteristics of your cable, or even worse render is useless. Check the
wires, one more time for nicks or cuts. If there are any, just whack the whole end off, and
start over.
2. Spread the wires apart, but be sure to hold onto the base of the jacket with your other
hand. You do not want the wires to become untwisted down inside the jacket. Category 5
cable must only have 1/2 of an inch of 'untwisted' wire at the end; otherwise it will be 'out
of spec'. At this point, you obviously have ALOT more than1/2ofaninchofun-twisted wire.
3. You have 2 end jacks, which must be installed on your cable. If you are using a pre-
made cable, with one of the ends whacked off, you only have one end to install –the
crossed over end. Below are two diagrams, which show how you need to arrange the
cables for each type of cable end. Decide at this point which end you are making and
examine the associated picture below.
Objective: Configuration of router, hub, switch etc. (using real devices or simulators).
1. Hub:
A Hub is just a connector that connects the wires coming from different sides. There is no signal
processing or regeneration. It is an electronic device that operates only on physical layers of the OSI
model. It is also known as a repeater as it transmits signal to every port except the port from where
signal is received. Also, hubs are not that intelligent in communication and processing information
for 2nd and 3rd layer.
2. Switch:
Switch is a point to point communication device. It operates at the data link layer of OSI model . It
uses switching table to find out the correct destination.
Basically, it is a kind of bridge that provides better connections. It is a kind of device that set up and
stops the connections according to the requirements needed at that time. It comes up with many
features such as flooding, filtering and frame transmission.
3. Router:
Routers are the multiport devices and more sophisticated as compared to repeaters and bridges. It
contains a routing table that enables it to make decision about the route i.e . to determine which of
several possible paths between the source and destination is the best for a particular transmission.
It works on the network layer 3 and used in LANs, MANs and WANs. It stores IP address and
maintains address on its own.
Difference between Hub, Switch and Router :
Sr.
No Hub Switch Router
Hub is a physical layer Switch is a data link layer Router is a network layer device
1.
device i.e. layer 1. device i.e. layer 2. i.e. layer 3.
A Hub works on the Switch works on the basis of A router works on the basis of IP
2.
basis of broadcasting. MAC address. address.
A Switch is a tele-
A Hub is a multiport A router reads the header of
communication device which
repeater in which a incoming packet and forward it
receives a message from any
signal introduced at the to the port for which it is
3. device connected to it and then
input of any port intended there by determines the
transmits the message only to
appears at the output of route. It can also perform
the device for which the
the all available ports. filtering and encapsulation.
message is intended.
At least single network At least single network is Router needs at least two
5.
is required to connect. required to connect. networks to connect.
Objective: Running and using services/commands like ping, traceroute, nslookup, arp, telnet,
ftp, etc
1. Trace route: Trace route is one of the most common utilities built into most operating systems.
It is useful for diagnosing network connections. It shows the path of a packet going from your
host/computer through each of the individual routes that handle the packet and time required for
it to go from one router to another up to the final host/destination.
2. Ping: The ping command is used to determine the ability of a user’s computer to reach a
destination computer. The main purpose of using this command is to verify if the computer can
connect over the network to another computer or network device. It also helps to find out the IP
address using the host name:
3. 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.
4. Nslookup: nslookup hostname - provides The Nslookup command is a DNS lookup utility. You
can use the following commands to look up the information for a selected hostname:An A record
for the hostname:
5. ARP:ARP stands for Address Resolution Protocol. Although network communications can
readily be thought of as an IP address, the packet delivery depends ultimately on the media
access control (MAC). This is where the protocol for address resolution comes into effect. You
can add the remote host IP address, which is an arp -a command, in case you have issues to
communicate with a given host. The ARP command provides information like Address, Flags,
Mask, IFace, Hardware Type, Hardware Address, etc.
6. FTP: FTP (File Transfer Protocol) is a standard network protocol used to exchange files
between computers on a private network or through the internet.
Experiment No: 15
Objective: Network packet analysis using tools like Wireshark, tcpdump, etc.
What is a Network Packet Analyzer?
This packet has a small unit of information that flows between the networks.
This is a well-defined method that constructs and verifies the network packets.
Every packet is connected with a link chain.
It is correctly transmitted and validated with the destination.
If any single pack becomes out of order, then the complete process will become suspended till the pack
comes in the correct order.
Best Network Packets Analyzer
In this article, you will get all types of information about Network Packets Analyzer and the top 10
Packet Analyzer Tools to manage the network and analyze the packets. You need a little more surface-
level knowledge so that you will understand what goes inside the network. Here you will get the list of
the top ten tools, to use on your network and understand their requirements.
1. Packet Capture
5. Tcpdump
2. Protocol Analysis
3. Real-Time Output
Top 10 Network Packet Analyzer Tools for
Features
Sysadmin & Security Analysts 2023
4. Filter Expressions
f.35.2.11111111