NP Lab
NP Lab
[Link]
MTech-II Semester
ACADEMIC YEAR
2025-2026
LABORATORY MANUAL
PREPARED BY
PROF. SRUTHI KRISHNA. U
Brindavan College of Engineering
Dwarakanagar, Bagalur Main Road, Yelahanka, Bengaluru – 560063
Affiliated to VTU Belagavi, Approved by AICTE, New Delhi, India, Accredited B++ by NAAC
Department of Computer Science and Engineering
MTech-II Semester
ACADEMIC YEAR
2025-2026
PREPARED BY
PROF. SRUTHI KRISHNA.U
Brindavan College of Engineering
Dwarakanagar, Bagalur Main Road, Yelahanka, Bengaluru – 560063
Affiliated to VTU Belagavi, Approved by AICTE, New Delhi, India, Accredited B++ by NAAC
Department of Computer Science and Engineering
LABORATORY CERTIFICATE
prescribed by Visvesvaraya Technological University, Belagavi of this Institute for the academic year
2025-26.
MARKS
DEPARTMENT VISION
To advance the intellectual capacity of the student community by imparting knowledge to be ingenious
entrepreneurs and competent professionals.
DEPARTMENT MISSION
• To disseminate technical knowledge with strong emphasis on curriculum development.
• To impart computing skills to make the graduates globally competitive.
• To inculcate value based professional ethics, become prevalent in industry and promoting research
activities.
Brindavan College of Engineering
Dwarakanagar, Bagalur Main Road, Yelahanka, Bengaluru – 560063
Affiliated to VTU Belagavi, Approved by AICTE, New Delhi, India, Accredited B++ by NAAC
Department of Computer Science and Engineering
➢ The executed results should be noted in their observations and get it verified by the concerned faculty.
➢ Observe good housekeeping practices. Keep the equipment’s in proper place after the conduction.
➢ Students must ensure that all the switches are in the OFF position; desktop is shutdown properly after
completion of the assignments.
➢ For circuits lab the components must returned properly.
➢ For power electronics lab wearing shoes is compulsory.
DON’Ts
➢ Do not come late to lab.
➢ Do not wear footwear and enter the lab(except power electronics lab).
➢ Do not insert pen drive/memory card to any computer in the lab.
The experiments conducted in this laboratory have helped in understanding network communication
concepts, protocol operations, network performance evaluation, and simulation-based analysis. The
practical exposure gained through these exercises has strengthened the theoretical concepts learned in
Computer Networks and Network Programming courses.
I express my sincere gratitude to the faculty members of the Department of Computer Science for their
valuable guidance and support throughout the laboratory sessions. I also acknowledge the use of NS2 as
an effective simulation tool for performing the prescribed network simulation experiments.
.
SYLLABUS:
1. Write a C program to implement daytime client/server program using TCP sockets
2. Write a TCP client/server program in which client sends three numbers to the server in a single
message. Server returns sum, difference and product as a result single message. Client program
should print the results appropriately
[Link] a C program that prints the IP layer and TCP layer socket options in a separate file
5. Setting up of network that carries various application protocols and analysing the
performances.
Theory:
a. What is a Socket?
A socket is an endpoint of a two-way communication link between two programs running on a network.
The Berkeley Sockets API, standardised under POSIX, provides a uniform interface for creating and using
sockets regardless of the underlying network protocol. A socket is identified by a combination of an IP
address and a port number.
b. TCP (Transmission Control Protocol)
TCP is a connection-oriented, reliable, byte-stream protocol. Before data can be exchanged, a three-way
handshake must establish a connection between the client and the server. TCP guarantees ordered, error-
free delivery of data segments and provides flow control and congestion control mechanisms.
c. Socket System Calls used in this Experiment
System Call Description
socket() Creates a new socket and returns a file descriptor. Parameters specify
address family (AF_INET), type (SOCK_STREAM for TCP), and
protocol (0).
bind() Associates the socket with a local address (IP + port). Mandatory on the
server side.
listen() Marks the socket as passive — ready to accept incoming connections.
The backlog parameter specifies the queue size.
accept() Blocks until a client connects. Returns a new connected socket
descriptor and fills in the client's address.
connect() Used by the client to initiate a connection to the server's address.
Triggers the TCP three-way handshake.
write() / read() Transfer data over the connected socket. Equivalent to writing/reading
a file descriptor.
close() Closes the socket file descriptor and, on the last close, sends a TCP FIN
to the peer.
E. Algorithm
3.1 Server Algorithm
START
8. Create a TCP socket using socket(AF_INET, SOCK_STREAM, 0). Store the returned file
descriptor in listen_fd.
9. Initialise a sockaddr_in structure with address family AF_INET, IP address INADDR_ANY, and
port 13000 (converted to network byte order with htons).
10. Call bind(listen_fd, ...) to bind the socket to the address.
11. Call listen(listen_fd, BACKLOG) to mark the socket as passive.
12. Enter an infinite loop:
13. a. Call accept() to block and wait for a client connection; receive conn_fd.
14. b. Call time(NULL) to get the current calendar time (seconds since epoch).
15. c. Format the time string using ctime() and write it to conn_fd.
16. d. Call close(conn_fd) to close the connected socket.
STOP (unreachable in practice — server runs forever).
3.2 Client Algorithm
START
17. Validate that the server IP address is provided as a command-line argument.
18. Create a TCP socket using socket(AF_INET, SOCK_STREAM, 0). Store in sock_fd.
19. Initialise a sockaddr_in structure with the server's IP (from argv[1]) and port 13000.
20. Call connect(sock_fd, ...) to connect to the server.
21. Call read() in a loop until all data is received; print each chunk to stdout.
22. Call close(sock_fd).
STOP.
4. Program
int main(void)
{
int listen_fd, conn_fd;
struct sockaddr_in srv_addr, cli_addr;
socklen_t cli_len;
char time_buf[64];
time_t ticks;
/* 4. Accept loop */
for (;;) {
cli_len = sizeof(cli_addr);
conn_fd = accept(listen_fd, (struct sockaddr *)&cli_addr, &cli_len);
if (conn_fd < 0) { perror("accept"); continue; }
close(listen_fd);
return 0;
}
4.2 Client – daytime_client.c
/* ============================================================
* Experiment 1 – Daytime Client (TCP)
* Compile: gcc daytime_client.c -o client
* Run : ./client [Link]
* ============================================================ */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
if (argc != 2) {
fprintf(stderr, "Usage: %s <server-ip>\n", argv[0]);
exit(EXIT_FAILURE);
}
/* 3. Connect to server */
if (connect(sock_fd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) {
perror("connect"); exit(EXIT_FAILURE);
}
/* 5. Close socket */
close(sock_fd);
return 0;
}
5. Output
Compile and run the server in one terminal and the client in a second terminal on the same machine (using
[Link] as the server IP).
On Terminal-1 Server
cd /mnt/Workspace location
gcc daytime_server.c -o server
./server
On Terminal-2 Client
cd /mnt/Workspace location
gcc daytime_client.c -o client
./client [Link]
6. Result
The program was executed successfully. The daytime server accepted the TCP connection from the client
and transmitted the current date and time as a formatted string. The client received and displayed the string
correctly. The TCP connection was gracefully terminated after the data transfer.
2. Write a TCP client/server program in which client sends three numbers to the server in a
single message. Server returns sum, difference and product as a result single message. Client
program should print the results appropriately.
Aim: To write a TCP client/server program in C where the client sends three integers to the server in a
single message using a C struct. The server computes the sum, difference, and product of the three numbers
and returns all three results to the client in a single reply message. The client prints the results
appropriately.
Theory:
a. Single Message Communication using Structs
In this experiment, instead of sending data as individual bytes or strings, both the client and server
exchange structured data using C structs. A struct packs multiple fields (integers in this case) into a
contiguous block of memory. When the entire struct is passed to write(), it is transmitted as a single
message in one system call. Similarly, read() on the receiving end fills the entire struct in one call. This
approach is efficient and clean for fixed-size data exchange.
b. How struct-based messaging works
1. Define identical struct types on both client and server sides.
2. Client fills the struct with user input values (a, b, c).
3. Client calls write(sock_fd, &in, sizeof(in)) — sends the entire struct as one message.
4. Server calls read(conn_fd, &in, sizeof(in)) — receives the entire struct in one call.
5. Server computes results, fills a result struct, and sends it back with write().
6. Client receives the result struct with read() and prints the values.
c. Key Concepts
Concept Explanation
C struct Groups multiple variables into one unit. Used here to pack 3 integers
into one message.
sizeof(struct) Returns the exact byte size of the struct. Used to tell write()/read()
how many bytes to send/receive.
Single write() write(fd, &struct, sizeof(struct)) sends the whole struct in one TCP
segment.
Single read() read(fd, &struct, sizeof(struct)) fills the whole struct from the socket
in one call.
Port 14000 Different from Exp 1 (port 13000) to avoid conflicts if both servers
run simultaneously.
Sum a+b+c
Difference a - b - c (first number minus the other two)
Product a*b*c
3. Algorithm
3.1 Server Algorithm
START
1. Create a TCP socket using socket(AF_INET, SOCK_STREAM, 0).
2. Bind the socket to port 14000 using bind().
3. Call listen() to mark the socket as passive.
4. Enter an infinite loop and call accept() to wait for a client.
5. Receive the input_msg struct (containing a, b, c) using a single read() call.
6. Compute: sum = a+b+c, difference = a-b-c, product = a*b*c.
7. Pack the three results into a result_msg struct.
8. Send the result_msg struct back to client using a single write() call.
9. Close the connected socket and go back to step 6.
STOP
3.2 Client Algorithm
START
1. Validate that the server IP is provided as command-line argument.
2. Create a TCP socket using socket().
3. Fill the server address structure with the given IP and port 14000.
4. Call connect() to establish connection with the server.
5. Prompt user to enter three integers a, b, c using scanf().
6. Pack the three integers into an input_msg struct.
7. Send the struct to server using a single write() call.
8. Receive the result_msg struct from server using a single read() call.
9. Print sum, difference, and product with proper labels.
10. Close the socket.
STOP
4. Program
4.1 Server – exp2_server.c
/* ============================================================
* Experiment 2 – TCP Server
* Client sends 3 numbers → Server returns sum, diff, product
* Compile: gcc exp2_server.c -o server2
* Run : ./server2
* ============================================================ */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(void)
{
int listen_fd, conn_fd;
struct sockaddr_in srv_addr, cli_addr;
socklen_t cli_len;
struct input_msg in;
struct result_msg res;
/* 2. Bind to port */
memset(&srv_addr, 0, sizeof(srv_addr));
srv_addr.sin_family = AF_INET;
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
srv_addr.sin_port = htons(PORT);
/* 3. Listen */
listen(listen_fd, BACKLOG);
printf("Server listening on port %d ...\n", PORT);
/* 4. Accept loop */
for (;;) {
cli_len = sizeof(cli_addr);
conn_fd = accept(listen_fd, (struct sockaddr *)&cli_addr, &cli_len);
if (conn_fd < 0) { perror("accept"); continue; }
/* 6. Compute results */
[Link] = in.a + in.b + in.c;
[Link] = in.a - in.b - in.c;
[Link] = in.a * in.b * in.c;
close(listen_fd);
return 0;
}
/* ============================================================
* Experiment 2 – TCP Client
* Sends 3 numbers, receives sum, difference, product
* Compile: gcc exp2_client.c -o client2
* Run : ./client2 [Link]
* ============================================================ */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
struct input_msg {
int a, b, c;
};
struct result_msg {
int sum;
int difference;
int product;
};
if (argc != 2) {
fprintf(stderr, "Usage: %s <server-ip>\n", argv[0]);
exit(EXIT_FAILURE);
}
/* 3. Connect to server */
if (connect(sock_fd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) {
perror("connect"); exit(EXIT_FAILURE);
}
/* 7. Display results */
printf("\n--- Results from Server ---\n");
printf("Sum : %d + %d + %d = %d\n", in.a, in.b, in.c, [Link]);
printf("Difference : %d - %d - %d = %d\n", in.a, in.b, in.c, [Link]);
printf("Product : %d x %d x %d = %d\n", in.a, in.b, in.c, [Link]);
close(sock_fd);
return 0;
}
5. Output
Run the server in Terminal 1 first, then run the client in Terminal 2 and enter three numbers when prompted.
6. Result
The program was executed successfully. The TCP client sent three integers (4, 6, 7) to the server in a single struct
message. The server computed the sum (17), difference (-9), and product (168) and returned all three results to the
client in a single reply message. The client received and printed the results correctly.
3. Write a C program that prints the IP layer and TCP layer socket options in a separate file.
Aim: To write a C program that creates a TCP socket and uses the getsockopt() system call to retrieve
and display socket options at three levels:
• SOL_SOCKET – general socket-level options
• IPPROTO_IP – IP layer options
• IPPROTO_TCP – TCP layer options
Objectives:
1. Understand the role of socket options in controlling network behaviour.
2. Identify and describe the key IP-layer socket options exposed by the kernel.
3. Identify and describe the key TCP-layer socket options exposed by the kernel.
4. Apply the getsockopt() / setsockopt() API to read and modify these options.
5. Analyse the default values and their practical implications.
Theory:
#include <sys/socket.h>
The level parameter selects the protocol layer that owns the option:
• SOL_SOCKET – options owned by the socket layer itself.
• IPPROTO_IP – options at the IP (network) layer.
• IPPROTO_TCP – options at the TCP (transport) layer.
c. IP_TTL
Specifies the initial Time To Live field placed in the IP header of every outgoing datagram. Each router that forwards the
packet decrements this counter; when it reaches zero the packet is discarded and an ICMP Time Exceeded message is sent
back. Default: 64 (Linux).
d. IP_TOS
Specifies the Type of Service byte in the IP header, used for Differentiated Services (DSCP) marking. Applications
requiring low latency (VoIP, video) set this to influence router queuing behaviour. Default: 0 (best effort).
e. IP_HDRINCL
When set on a raw socket, the application constructs the entire IP header manually. Not applicable to TCP sockets (always
returns 0). Useful for packet injection tools.
f. IP_MULTICAST_TTL / IP_MULTICAST_LOOP
Control multicast behaviour. IP_MULTICAST_TTL limits the scope of multicast packets (1 = link-local only).
IP_MULTICAST_LOOP controls whether the host's own network stack receives a copy of sent multicast datagrams.
i. TCP_MAXSEG (MSS)
The Maximum Segment Size caps the payload of individual TCP segments. The actual negotiated MSS is determined during
the three-way handshake (typically 1460 bytes for Ethernet). Before any connection is established the kernel returns the
conservative default of 536 bytes.
k. TCP_INFO
Read-only struct tcp_info providing a rich snapshot of the TCP state machine: current state, RTO, RTT, cwnd, ssthresh,
bytes sent/received, retransmit counters, etc. Invaluable for performance diagnosis without external tools.
Pre-Requisites
• GNU/Linux operating system (Ubuntu 20.04+ or equivalent)
• GCC compiler (gcc --version)
• Basic understanding of the TCP/IP stack
• Familiarity with POSIX socket API: socket(), bind(), connect()
• Text editor or IDE (VS Code, gedit, vim)
Algorithm
• Include required header files: <sys/socket.h>, <netinet/in.h>, <netinet/tcp.h>.
• Call socket(AF_INET, SOCK_STREAM, 0) to create a TCP socket; check return value.
o Call print_socket_options(): for each SOL_SOCKET option call getsockopt() and print the result.
• Call print_ip_options(): for each IPPROTO_IP option call getsockopt() and print the result.
o Call print_tcp_options(): for each IPPROTO_TCP option call getsockopt() and print the result; also read
struct tcp_info.
• Print error messages (using strerror(errno)) for any option that fails.
• Close the socket with close(sockfd) and exit.
Program (socket_options.c)
/*
* socket_options.c
* Program to display IP layer and TCP layer socket options
* Demonstrates getsockopt() for both IPPROTO_IP and IPPROTO_TCP levels
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
printf("\n");
}
printf("\n");
}
printf("\n");
}
int main(void) {
int sockfd;
printf("\n");
printf("************************************************************\n");
printf("* TCP/IP Socket Options Display Program *\n");
printf("************************************************************\n");
close(sockfd);
printf("============================================================\n");
printf(" [+] Socket closed. Program completed successfully.\n");
printf("============================================================\n\n");
return 0;
}
Compilation and Execution
Compile
$ gcc -Wall -o socket_options socket_options.c
Run
$ ./socket_options
OUTPUT ANALYSIS
Requirements
• Linux / WSL / Ubuntu
• GCC Compiler
• Java JDK
• Terminal
Theory
A socket is an endpoint of communication between two machines over a network. Socket
programming allows processes on different systems to communicate using TCP or UDP protocols.
• TCP (Transmission Control Protocol):
Connection-oriented, reliable communication.
• UDP (User Datagram Protocol):
Connectionless, faster but unreliable.
Socket communication follows a client-server model:
• Server waits for connection
• Client initiates connection
int main() {
int server_fd, client_fd;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
char buffer[BUFSIZE];
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(PORT);
printf("Server waiting...\n");
client_fd = accept(server_fd, (struct sockaddr*)&addr, &addrlen);
while (1) {
memset(buffer, 0, BUFSIZE);
recv(client_fd, buffer, BUFSIZE, 0);
if (strncmp(buffer, "exit", 4) == 0)
break;
printf("Server: ");
fgets(buffer, BUFSIZE, stdin);
send(client_fd, buffer, strlen(buffer), 0);
}
close(client_fd);
close(server_fd);
return 0;
}
int main() {
int sockfd;
struct sockaddr_in addr;
char buffer[BUFSIZE];
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
inet_pton(AF_INET, "[Link]", &addr.sin_addr);
printf("Connected to server\n");
while (1) {
printf("Client: ");
fgets(buffer, BUFSIZE, stdin);
if (strncmp(buffer, "exit", 4) == 0)
break;
memset(buffer, 0, BUFSIZE);
recv(sockfd, buffer, BUFSIZE, 0);
close(sockfd);
return 0;
}
Output
Result
Thus, TCP client-server communication using C was successfully implemented.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
int sockfd;
char buffer[BUFSIZE];
struct sockaddr_in server_addr, client_addr;
socklen_t len = sizeof(client_addr);
// Bind socket
bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
while (1) {
memset(buffer, 0, BUFSIZE);
if (strncmp(buffer, "exit", 4) == 0)
break;
close(sockfd);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
int sockfd;
char buffer[BUFSIZE];
struct sockaddr_in server_addr;
socklen_t len = sizeof(server_addr);
while (1) {
printf("[CLIENT] Message: ");
fgets(buffer, BUFSIZE, stdin);
memset(buffer, 0, BUFSIZE);
close(sockfd);
return 0;
}
Result:
Thus, the UDP client–server programs were successfully implemented using socket
programming in C. The server was able to receive messages from the client using recvfrom()
and send responses using sendto(). The client successfully transmitted data to the server and
received replies.
Hence, communication using the UDP (connectionless) protocol was demonstrated
successfully.
UDP socket communication using SOCK_DGRAM is verified
Message exchange between client and server is achieved
Experiment is completed successfully.
import [Link].*;
import [Link].*;
String message;
while (true) {
message = [Link]();
[Link]("[CLIENT] " + message);
if ([Link]("exit"))
break;
[Link](reply);
[Link]();
}
[Link]();
[Link]();
[Link]("[SERVER] Connection closed");
} catch (Exception e) {
[Link](e);
}
}
}
String message;
while (true) {
[Link]("[CLIENT] Message: ");
message = [Link]();
[Link](message);
[Link]();
if ([Link]("exit"))
break;
[Link]();
[Link]("[CLIENT] Connection closed");
} catch (Exception e) {
[Link](e);
}
}
}
Compilation:
javac [Link]
javac [Link]
java Server
java Client
Output:
Result:
Thus, the TCP client–server program using Java socket programming was successfully
implemented. The server and client were able to establish a connection using ServerSocket
and Socket classes, and successfully exchange messages using input and output streams.
• TCP connection established successfully
• Bidirectional communication achieved
• Client–server model demonstrated using Java sockets
InputStream in = [Link]();
FileOutputStream fos = new FileOutputStream("[Link]");
} catch (Exception e) {
[Link](e);
}
}
}
[Link]();
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
Note: in the terminal echo "Hello Network Programming Lab" > [Link]
Then type ls you can find a file named [Link]
Now compile: javac FileServer.c in one terminal and in the other javac [Link]
Again run: java FileServer in one terminal and java FileServer in the other terminal
Output:
Result:
Thus, the file transfer between client and server using Java socket programming was
successfully implemented. The client successfully sent a file using Socket output stream, and
the server received and stored it using FileOutputStream.
• File successfully transmitted over TCP
• Client–server communication established
• File I/O with sockets demonstrated
[Link] using OPNET Network Simulator [NS2 simulator]
Aim: To create and analyze different network topologies (Star, Bus, Ring, Mesh, Tree) using
NS-3 simulator and visualize them using NetAnim.
Software Required
• NS-3 (ns-3-dev)
• Ubuntu (WSL2 on Windows 11)
• NetAnim
• CMake, Qt5 tools
1. Network Topology
A topology defines how nodes are connected in a network.
Types:
• Star (central node)
• Bus (shared medium)
• Ring (circular connection)
• Mesh (fully connected)
• Tree (hierarchical)
1. Star Topology
int main()
{
NodeContainer nodes;
[Link](5);
CsmaHelper csma;
[Link]("DataRate", StringValue("100Mbps"));
[Link]("Delay", TimeValue(MilliSeconds(2)));
InternetStackHelper stack;
[Link](nodes);
MobilityHelper mobility;
[Link]("ns3::ConstantPositionMobilityModel");
[Link](nodes);
AnimationInterface anim("[Link]");
[Link](0)->GetObject<MobilityModel>()->SetPosition(Vector(0,0,0));
[Link](1)->GetObject<MobilityModel>()->SetPosition(Vector(50,0,0));
[Link](2)->GetObject<MobilityModel>()->SetPosition(Vector(100,0,0));
[Link](3)->GetObject<MobilityModel>()->SetPosition(Vector(150,0,0));
[Link](4)->GetObject<MobilityModel>()->SetPosition(Vector(200,0,0));
Simulator::Run();
Simulator::Destroy();
}
Run:
./ns3 run scratch/star-topology
Output:
• [Link] generated
5b. Implementation of various MAC protocols:
Aim: To implement and analyze different MAC (Medium Access Control) protocols using
NS2 and observe their behavior in a network environment.
Objective
• To understand MAC layer functioning in wireless networks.
• To simulate different MAC protocols in NS2.
• To compare performance based on packet delivery, delay, and throughput.
Theory: The MAC layer controls how nodes access the shared communication medium.
Common MAC protocols in NS2:
1. MAC 802.11
• Used in wireless LANs (Wi-Fi)
• Uses CSMA/CA (Collision Avoidance)
• Includes RTS/CTS mechanism
2. MAC 802.3 (Ethernet)
• Wired LAN protocol
• Uses CSMA/CD (Collision Detection)
3. MAC/802_11 variants in NS2
• Basic 802.11
• MAC/802_11Ext (extended features)
NS2 Implementation
A. TCL Script (Wireless MAC 802.11)
set ns [new Simulator]
create-god 3
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
# Node positions
$n0 set X_ 50
$n0 set Y_ 50
# Traffic
set tcp [new Agent/TCP]
set sink [new Agent/TCPSink]
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam [Link] &
exit 0
}
$ns run
Output:
y:~$ grep -c "^+" [Link]
0
y:~$ grep -c "^r" [Link]
10
Y:~$ grep -c "^d" [Link]
0
Y:~$ awk '$1=="r"{count++} END{print count}' [Link]
10
Objective:
• To understand routing in wireless networks
• To simulate different MANET routing protocols in NS2
• To compare performance based on packet delivery ratio, delay, and throughput
• To analyze trace files generated by NS2
Software required
• NS2 (Network Simulator 2.35)
• Ubuntu Linux
• AWK scripting tool
THEORY
Routing Protocols in NS2
Routing protocols determine how data packets travel from source to destination.
1. DSDV (Destination-Sequenced Distance Vector)
• Proactive protocol
• Maintains routing tables
• Periodic updates
2. AODV (Ad hoc On-Demand Distance Vector)
• Reactive protocol
• Routes created on demand
• Uses RREQ and RREP
3. DSR (Dynamic Source Routing)
• Reactive protocol
• Entire route stored in packet header
create-god 4
# TCP connection
set tcp [new Agent/TCP]
set sink [new Agent/TCPSink]
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam [Link] &
exit 0
}
$ns run
Output:
ns [Link]
Packet Sent: grep -c "^+" [Link]
Throughput
awk '$1=="r"{count++} END{print "Packets received =", count}' [Link]
RESULT
The routing protocols were successfully implemented in NS2. Performance was analysed
using trace files based on packet delivery ratio, throughput, and packet loss.
Aim: To simulate TCP/IP traffic in NS2 and analyze its performance under different
network conditions such as congestion, delay, and packet loss.
Objective
• To study TCP/IP behavior in wired and wireless networks
• To understand TCP congestion control mechanisms
• To analyze performance metrics like throughput, delay, and packet loss
• To generate and evaluate NS2 trace files
Software required
• NS2 (Network Simulator 2.35)
• Ubuntu Linux
• AWK / Gnuplot (for analysis)
THEORY:
a. TCP/IP Protocol
TCP/IP is the backbone protocol suite of the Internet.
TCP (Transmission Control Protocol)
• Connection-oriented
• Reliable data delivery
• Uses congestion control (slow start, congestion avoidance)
b. IP (Internet Protocol)
• Provides addressing and routing
• Unreliable and connectionless
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
# TCP Agent
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
# TCP Sink
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink
# FTP Traffic
set ftp [new Application/FTP]
$ftp attach-agent $tcp
proc finish {} {
global ns tf nf
$ns flush-trace
close $tf
close $nf
exit 0
}
$ns run
Output:
Result:
The TCP/IP protocol was successfully simulated using NS2. TCP traffic was generated
between two nodes connected through a duplex link. The trace analysis showed successful
packet transmission with zero packet loss and a Packet Delivery Ratio (PDR) of 100%,
demonstrating reliable communication provided by TCP.
Objective:
• To simulate multiple application protocols in a network.
• To study the behavior of TCP and UDP traffic.
• To compare performance metrics such as throughput, packet delivery ratio, and packet
loss.
• To analyze the generated trace files.
Software required:
• NS2 (Network Simulator 2.35)
• Ubuntu Linux
• AWK (for trace analysis)
Theory:
TCP (Transmission Control Protocol)
• Connection-oriented protocol.
• Reliable data delivery.
• Uses acknowledgments and retransmissions.
• Common applications: FTP, HTTP, Email.
UDP (User Datagram Protocol)
• Connectionless protocol.
• Faster but unreliable.
• No acknowledgments.
• Common applications: Video streaming, VoIP, Online gaming.
FTP Traffic
• Uses TCP.
• Reliable file transfer.
CBR Traffic
• Uses UDP.
• Generates packets at a constant rate.
TCL PROGRAM
# Create simulator
set ns [new Simulator]
# Trace files
set tf [open [Link] w]
$ns trace-all $tf
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
# Links
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
# Schedule traffic
$ns at 1.0 "$ftp start"
$ns at 2.0 "$cbr start"
proc finish {} {
global ns tf nf
$ns flush-trace
close $tf
close $nf
exit 0
}
$ns run
PROCEDURE
1. Open Terminal.
2. Create TCL file:
nano [Link]
3. type the program and save.
4. Run simulation:
ns [Link]
5. Verify trace file creation:
ls -l [Link]
PERFORMANCE ANALYSIS
Total Packets Sent
grep -c "^+" [Link]
Total Packets Received
grep -c "^r" [Link]
Packet Loss
grep -c "^d" [Link]
Packet Delivery Ratio
awk '
$1=="+"{s++}
$1=="r"{r++}
END{
if(s>0)
print "PDR =", (r/s)*100,"%"
}'
[Link]
Output:
Result:
A network carrying multiple application protocols (FTP over TCP and CBR over UDP) was
successfully simulated using NS2. The generated trace file was analyzed to measure packet
transmission performance, packet delivery ratio, throughput, and packet loss.
6. Comparison of TCP/IP, Sockets, and Pipes – Performance Analysis
Aim: To study, implement, and compare TCP/IP communication, Socket programming, and
Pipe communication mechanisms and analyze their performance based on speed, reliability,
complexity, and communication capability.
Objective:
• To understand different inter-process and network communication mechanisms.
• To implement communication using TCP/IP, Sockets, and Pipes.
• To compare their performance characteristics.
• To identify the most suitable mechanism for different applications.
Software required:
• Ubuntu Linux
• GCC Compiler
• Terminal
• C Programming Language
Theory:
a. TCP/IP
TCP/IP is a communication protocol suite used for communication over networks.
Features:
• Reliable communication
• Error detection and correction
• Supports communication across different networks
• Used in Internet applications
b. Socket Programming
A socket is an endpoint for communication between two processes over a network.
Features:
• Client-server architecture
• Supports TCP and UDP
• Network communication
• Widely used in distributed systems
c. Pipes
A pipe is a mechanism for communication between processes running on the same system.
Features:
• Fast communication
• Local machine only
• Simple implementation
• Used for parent-child process communication
ALGORITHM
TCP/IP Communication
1. Create sender and receiver.
2. Establish TCP connection.
3. Send data.
4. Receive data.
5. Close connection.
Socket Communication
1. Create socket.
2. Bind socket.
3. Listen for connection.
4. Accept connection.
5. Exchange data.
Pipe Communication
1. Create pipe.
2. Fork process.
3. Write data into pipe.
4. Read data from pipe.
5. Close pipe.
PROGRAMS
A. Pipe Communication
#include <stdio.h>
#include <unistd.h>
int main()
{
int fd[2];
char msg[] = "Hello Pipe";
char buffer[50];
pipe(fd);
if(fork()==0)
{
read(fd[0], buffer, sizeof(buffer));
printf("Received: %s\n", buffer);
}
else
{
write(fd[1], msg, sizeof(msg));
}
return 0;
}
Compile:
gcc pipe.c -o pipe
./pipe
B. TCP Socket Server
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
int sockfd, newsockfd;
struct sockaddr_in server;
char msg[100];
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(9000);
bind(sockfd,(struct sockaddr*)&server,sizeof(server));
listen(sockfd,5);
newsockfd = accept(sockfd,NULL,NULL);
read(newsockfd,msg,sizeof(msg));
printf("Message: %s\n",msg);
close(sockfd);
return 0;
}
int main()
{
int sockfd;
struct sockaddr_in server;
sockfd = socket(AF_INET,SOCK_STREAM,0);
server.sin_family = AF_INET;
server.sin_port = htons(9000);
server.sin_addr.s_addr = inet_addr("[Link]");
connect(sockfd,(struct sockaddr*)&server,sizeof(server));
write(sockfd,"Hello Socket",12);
close(sockfd);
return 0;
}
Compile:
gcc server.c -o server
gcc client.c -o client
Run:
./server
./client
PROCEDURE
1. Create source files.
2. Compile programs using GCC.
3. Execute programs.
4. Observe communication.
5. Measure performance parameters.
6. Compare results.
OBSERVATION TABLE
Parameter TCP/IP Socket Pipe
Communication Type Network Network Local
Reliability High High High
Speed Medium Medium Very High
Complexity High Medium Low
Remote Communication Yes Yes No
Resource Usage Medium Medium Low
PERFORMANCE COMPARISON
Feature TCP/IP Socket Pipe
Data Transfer Speed Good Good Excellent
Error Handling Excellent Excellent Limited
Feature TCP/IP Socket Pipe
Scalability Excellent Good Poor
Network Support Yes Yes No
Ease of Implementation Moderate Moderate Easy
RESULT
The communication mechanisms TCP/IP, Sockets, and Pipes were successfully studied and
compared. Pipes provide the highest speed for local communication, sockets are suitable for
client-server applications, and TCP/IP is the preferred choice for reliable communication over
networks. Therefore, the best mechanism depends on the application requirements.
CONCLUSION
• Pipes are best for communication between processes on the same machine.
• Sockets are best for distributed client-server applications.
• TCP/IP is best for reliable communication across networks.
• No single mechanism is universally best; the choice depends on the communication
environment and application requirements.