0% found this document useful (0 votes)
10 views58 pages

NP Lab

The document is a laboratory manual for the Network Programming Laboratory (MSCSL207) at Brindavan College of Engineering for the academic year 2025-2026, prepared by Prof. Sruthi Krishna U. It includes details on the course objectives, laboratory guidelines, a syllabus with practical experiments on TCP/IP-based client-server applications, and specific programming assignments using C and network simulation tools. The manual emphasizes hands-on experience in network communication concepts and protocol behavior while adhering to academic standards and ethical practices in the lab environment.

Uploaded by

veenabjmanjunath
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views58 pages

NP Lab

The document is a laboratory manual for the Network Programming Laboratory (MSCSL207) at Brindavan College of Engineering for the academic year 2025-2026, prepared by Prof. Sruthi Krishna U. It includes details on the course objectives, laboratory guidelines, a syllabus with practical experiments on TCP/IP-based client-server applications, and specific programming assignments using C and network simulation tools. The manual emphasizes hands-on experience in network communication concepts and protocol behavior while adhering to academic standards and ethical practices in the lab environment.

Uploaded by

veenabjmanjunath
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

[Link]

MTech-II Semester

NETWORK PROGRAMMING LABORATORY


MSCSL207

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

NETWORK PROGRAMMING LABORATORY


MSCSL207

ACADEMIC YEAR
2025-2026

Name of the Student: ____________________________________


University Seat number: _________________________________
Batch: ________________________________________________

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

This is to certify that Mr. / Ms. _______________________________________________ bearing USN

___________________ of ________________ semester and ______________ section has satisfactorily

completed the course of experiments in the NETWORK PROGRAMMING LABORATORY MSCSL207

prescribed by Visvesvaraya Technological University, Belagavi of this Institute for the academic year

2025-26.

MARKS

Maximum Marks Marks Obtained

Signature of Faculty-In-Charge Head of the Department


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

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

DOs & DON’Ts IN LABORATORY


DO’s
➢ Be on time and students should carry observation and completed records in all aspects.
➢ Dress code & wearing ID card is compulsory.

➢ Electronic gadgets are not allowed inside the lab.

➢ Students should be at their concerned desktop.


➢ After execution the students should get it verified by the concerned faculty.

➢ 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 touch server computer.


➢ Do not leave the lab without the permission of the faculty in-charge.

➢ 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.

➢ Do not upload, delete or alter any software files.


PREFACE
This laboratory record has been prepared as a part of the curriculum requirements for the course "Network
Programming Laboratory" (Course Code: MSCSL207). The course is designed to provide practical
knowledge of network programming concepts, client-server communication, socket programming, and
computer network simulation techniques.
The laboratory experiments include the implementation of TCP/IP-based client-server applications using
socket programming in the C programming language. These experiments provide hands-on experience in
establishing network communication, understanding protocol behavior, and developing applications based
on the TCP/IP protocol suite.
The syllabus originally prescribed the use of OPNET Network Simulator for network simulation and
performance analysis. However, due to the availability and accessibility of simulation tools, the network
simulation experiments were carried out using Network Simulator 2 (NS2). NS2 is a widely used open-
source network simulation platform that supports the modelling and analysis of network topologies,
routing protocols, MAC protocols, TCP/IP mechanisms, and application-layer traffic.
The simulation experiments performed using NS2 include:
1. Setting up of various network topologies.
2. Implementation of various MAC protocols.
3. Measurement of routing protocols.
4. Analysis of TCP/IP protocols under various mechanisms.
5. Setting up networks carrying various application protocols and analyzing their performance.
6. Comparison of TCP/IP, Sockets, and Pipes.

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.
.

Prof. Sruthi Krishna U


NETWORK PROGRAMMING LABORATORY SYLLABUS
***************************************************************
Course Code MSCSL207 CIE Marks: 50
Number of Contact Hours/Week 0:2:0 SEE Marks: 50
Total Number of Lab Contact Hours 36 Exam Hours:03
Credits – 2

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

[Link] on Socket Programming using C and Java

5. Exercises using OPNET Network Simulator.

1. Setting up of various network topologies

2. Implementation of various MAC protocols

3. Measurement of routing protocols

4. Analysis of TCP/IP protocol under various mechanisms

5. Setting up of network that carries various application protocols and analysing the
performances.

6. Comparison of TCP/IP, Socket, Pipes. Analyse which is the best


1. Write a C program to implement daytime client/server program using TCP sockets
Aim: To write a C program that implements a Daytime client and a Daytime server communicating over a TCP
socket. The server listens on a well-known port, accepts a connection, sends the current date and time as a string,
and closes the connection. The client connects to the server, reads the date-time string, prints it on the console, and
exits.

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.

d. Client–Server Interaction Flow


The sequence of socket calls for a TCP daytime exchange is as follows:
1. Server creates a listening socket with socket(), binds it to port 13000 with bind(), and calls
listen().
2. Server blocks on accept(), waiting for an incoming connection.
3. Client creates a socket with socket(), fills the server address structure, and calls connect().
4. The TCP three-way handshake completes; accept() on the server returns a new connected socket.
5. Server obtains the current time using time() and formats it with ctime(), then sends it via write().
6. Client reads the data with read() and prints it to standard output.
7. Server calls close() on the connected socket; client calls close() on its socket.

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

4.1 Server – daytime_server.c


/* ============================================================
* Experiment 1 – Daytime Server (TCP)
* Compile: gcc daytime_server.c -o server
* Run : ./server
* ============================================================ */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define PORT 13000


#define BACKLOG 5

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;

/* 1. Create TCP socket */


listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) { perror("socket"); exit(EXIT_FAILURE); }

/* 2. Bind to address and 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);

if (bind(listen_fd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) {


perror("bind"); exit(EXIT_FAILURE);
}

/* 3. Listen for incoming connections */


if (listen(listen_fd, BACKLOG) < 0) { perror("listen"); exit(EXIT_FAILURE); }
printf("Daytime 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; }

printf("Connection from: %s\n", inet_ntoa(cli_addr.sin_addr));

/* 5. Get current time and send to client */


ticks = time(NULL);
snprintf(time_buf, sizeof(time_buf), "%.24s\r\n", ctime(&ticks));
write(conn_fd, time_buf, strlen(time_buf));

/* 6. Close connected socket */


close(conn_fd);
}

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>

#define PORT 13000

int main(int argc, char *argv[])


{
int sock_fd;
struct sockaddr_in srv_addr;
char recv_buf[128];
int n;

if (argc != 2) {
fprintf(stderr, "Usage: %s <server-ip>\n", argv[0]);
exit(EXIT_FAILURE);
}

/* 1. Create TCP socket */


sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd < 0) { perror("socket"); exit(EXIT_FAILURE); }
/* 2. Fill server address structure */
memset(&srv_addr, 0, sizeof(srv_addr));
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(PORT);

if (inet_pton(AF_INET, argv[1], &srv_addr.sin_addr) <= 0) {


fprintf(stderr, "Invalid address: %s\n", argv[1]);
exit(EXIT_FAILURE);
}

/* 3. Connect to server */
if (connect(sock_fd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) {
perror("connect"); exit(EXIT_FAILURE);
}

/* 4. Read response and print */


while ((n = read(sock_fd, recv_buf, sizeof(recv_buf) - 1)) > 0) {
recv_buf[n] = '\0';
printf("Date/Time from server: %s", recv_buf);
}

/* 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>

#define PORT 14000


#define BACKLOG 5

/* Single message carrying three integers from client */


struct input_msg {
int a, b, c;
};

/* Single message carrying three results back to client */


struct result_msg {
int sum;
int difference;
int product;
};

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;

/* 1. Create TCP socket */


listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) { perror("socket"); exit(EXIT_FAILURE); }

/* 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);

if (bind(listen_fd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) {


perror("bind"); exit(EXIT_FAILURE);
}

/* 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; }

printf("Connection from: %s\n", inet_ntoa(cli_addr.sin_addr));

/* 5. Receive all 3 numbers in ONE read call */


read(conn_fd, &in, sizeof(in));
printf("Received: a=%d b=%d c=%d\n", in.a, in.b, in.c);

/* 6. Compute results */
[Link] = in.a + in.b + in.c;
[Link] = in.a - in.b - in.c;
[Link] = in.a * in.b * in.c;

/* 7. Send all 3 results in ONE write call */


write(conn_fd, &res, sizeof(res));
close(conn_fd);
}

close(listen_fd);
return 0;
}

4.2 Client – exp2_client.c

/* ============================================================
* 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>

#define PORT 14000

struct input_msg {
int a, b, c;
};

struct result_msg {
int sum;
int difference;
int product;
};

int main(int argc, char *argv[])


{
int sock_fd;
struct sockaddr_in srv_addr;
struct input_msg in;
struct result_msg res;

if (argc != 2) {
fprintf(stderr, "Usage: %s <server-ip>\n", argv[0]);
exit(EXIT_FAILURE);
}

/* 1. Create TCP socket */


sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd < 0) { perror("socket"); exit(EXIT_FAILURE); }

/* 2. Fill server address */


memset(&srv_addr, 0, sizeof(srv_addr));
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(PORT);
inet_pton(AF_INET, argv[1], &srv_addr.sin_addr);

/* 3. Connect to server */
if (connect(sock_fd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)) < 0) {
perror("connect"); exit(EXIT_FAILURE);
}

/* 4. Read 3 numbers from user */


printf("Enter three numbers: ");
scanf("%d %d %d", &in.a, &in.b, &in.c);

/* 5. Send all 3 numbers in ONE write call */


write(sock_fd, &in, sizeof(in));

/* 6. Receive all 3 results in ONE read call */


read(sock_fd, &res, sizeof(res));

/* 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:

a. Socket Options Overview


Every socket in a POSIX system has a set of attributes that govern its behavior—send/receive buffer sizes, timeout values,
keep-alive parameters, etc. These are manipulated at runtime through two symmetric system calls:

#include <sys/socket.h>

int getsockopt(int sockfd, int level, int optname,


void *optval, socklen_t *optlen);

int setsockopt(int sockfd, int level, int optname,


const void *optval, socklen_t optlen);

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.

b. IP Layer Options (IPPROTO_IP)


Options at the IP level control how IP datagrams are formed and received by the socket.

Option Name Data Type Default Description


IP_TTL int 64 Time To Live – max hops before packet is dropped
IP_TOS int 0 Type of Service – priority/delay/throughput hint
IP_HDRINCL int (bool) 0 If 1, application provides its own IP header
IP_RECVTTL int (bool) 0 Enable receipt of TTL value via ancillary data
IP_RECVTOS int (bool) 0 Enable receipt of TOS value via ancillary data
IP_MULTICAST_T u_char 1 TTL for outgoing multicast datagrams
TL
IP_MULTICAST_L u_char 1 Enable/disable loopback of multicast datagrams
OOP

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.

g. TCP Layer Options (IPPROTO_TCP)


TCP options give fine-grained control over congestion, buffering, keep-alive probing, and the connection handshake.

Option Name Data Type Default Description


TCP_NODELAY int (bool) 0 Disable Nagle algorithm; send immediately
TCP_MAXSEG int 536 Maximum segment size (MSS) for outgoing segments
TCP_KEEPIDLE int 7200 Seconds idle before keepalive probes begin
TCP_KEEPINTVL int 75 Interval (s) between keepalive probes
TCP_KEEPCNT int 9 Number of unanswered probes before connection drop
TCP_CORK int (bool) 0 Accumulate data (cork the socket) before sending

TCP_WINDOW_CLA int 0 Bound the size of the advertised receive window


MP

TCP_DEFER_ACCE int 0 Delay accept until data arrives; 0 = disabled


PT

TCP_SYNCNT int 6 Number of SYN retransmissions before giving up


TCP_LINGER2 int 60 FIN_WAIT2 timeout in seconds
TCP_INFO tcp_info struct Kernel-level TCP diagnostics (read-only struct)
h. TCP_NODELAY
Disables the Nagle algorithm, which normally coalesces small writes into larger segments. Setting TCP_NODELAY is
essential for interactive protocols (SSH, Telnet, financial trading) where latency matters more than throughput efficiency.

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.

j. TCP Keepalive Trio


Three options work together to detect dead peers. TCP_KEEPIDLE sets the idle threshold (default 7200 s). After that, the
kernel sends TCP_KEEPCNT probes spaced TCP_KEEPINTVL seconds apart. If no ACK is received the connection is
terminated. These defaults can be reduced dramatically for server applications that need to reclaim resources faster.

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>

/* Helper to print a separator line */


void print_separator(const char *title) {
printf("\n");
printf("============================================================\n");
printf(" %s\n", title);
printf("============================================================\n");
}

/* Helper to print option result */


void print_option(const char *name, int value) {
printf(" %-30s : %d\n", name, value);
}

/* Print all IP layer (IPPROTO_IP) socket options */


void print_ip_options(int sockfd) {
int val;
socklen_t len = sizeof(val);

print_separator("IP LAYER SOCKET OPTIONS (IPPROTO_IP)");

/* IP_TTL: Time To Live */


if (getsockopt(sockfd, IPPROTO_IP, IP_TTL, &val, &len) == 0)
print_option("IP_TTL (Time To Live)", val);
else
printf(" %-30s : Error (%s)\n", "IP_TTL", strerror(errno));

/* IP_TOS: Type of Service */


if (getsockopt(sockfd, IPPROTO_IP, IP_TOS, &val, &len) == 0)
print_option("IP_TOS (Type of Service)", val);
else
printf(" %-30s : Error (%s)\n", "IP_TOS", strerror(errno));

/* IP_HDRINCL: Include IP header */


if (getsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &val, &len) == 0)
print_option("IP_HDRINCL (Header Include)", val);
else
printf(" %-30s : Error (%s)\n", "IP_HDRINCL", strerror(errno));

/* IP_RECVTTL: Receive TTL */


if (getsockopt(sockfd, IPPROTO_IP, IP_RECVTTL, &val, &len) == 0)
print_option("IP_RECVTTL (Receive TTL)", val);
else
printf(" %-30s : Error (%s)\n", "IP_RECVTTL", strerror(errno));

/* IP_RECVTOS: Receive TOS */


if (getsockopt(sockfd, IPPROTO_IP, IP_RECVTOS, &val, &len) == 0)
print_option("IP_RECVTOS (Receive TOS)", val);
else
printf(" %-30s : Error (%s)\n", "IP_RECVTOS", strerror(errno));

/* IP_MULTICAST_TTL: Multicast TTL */


unsigned char mttl;
socklen_t mlen = sizeof(mttl);
if (getsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, &mlen) == 0)
printf(" %-30s : %d\n", "IP_MULTICAST_TTL", (int)mttl);
else
printf(" %-30s : Error (%s)\n", "IP_MULTICAST_TTL", strerror(errno));

/* IP_MULTICAST_LOOP: Multicast loopback */


unsigned char mloop;
mlen = sizeof(mloop);
if (getsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_LOOP, &mloop, &mlen) == 0)
printf(" %-30s : %d\n", "IP_MULTICAST_LOOP", (int)mloop);
else
printf(" %-30s : Error (%s)\n", "IP_MULTICAST_LOOP", strerror(errno));

printf("\n");
}

/* Print all TCP layer (IPPROTO_TCP) socket options */


void print_tcp_options(int sockfd) {
int val;
socklen_t len = sizeof(val);

print_separator("TCP LAYER SOCKET OPTIONS (IPPROTO_TCP)");

/* TCP_NODELAY: Disable Nagle algorithm */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &val, &len) == 0)
print_option("TCP_NODELAY (Nagle Disabled)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_NODELAY", strerror(errno));

/* TCP_MAXSEG: Maximum segment size */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_MAXSEG, &val, &len) == 0)
print_option("TCP_MAXSEG (Max Segment Size)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_MAXSEG", strerror(errno));

/* TCP_KEEPIDLE: Keep-alive idle time */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &val, &len) == 0)
print_option("TCP_KEEPIDLE (Keepalive Idle)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_KEEPIDLE", strerror(errno));

/* TCP_KEEPINTVL: Keep-alive interval */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &val, &len) == 0)
print_option("TCP_KEEPINTVL (Keepalive Interval)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_KEEPINTVL", strerror(errno));

/* TCP_KEEPCNT: Keep-alive probe count */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, &val, &len) == 0)
print_option("TCP_KEEPCNT (Keepalive Probes)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_KEEPCNT", strerror(errno));

/* TCP_WINDOW_CLAMP: Window clamp value */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_WINDOW_CLAMP, &val, &len) == 0)
print_option("TCP_WINDOW_CLAMP (Window Clamp)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_WINDOW_CLAMP", strerror(errno));

/* TCP_CORK: Accumulate data before sending */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_CORK, &val, &len) == 0)
print_option("TCP_CORK (Cork/Accumulate)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_CORK", strerror(errno));

/* TCP_DEFER_ACCEPT: Defer accept until data arrives */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &val, &len) == 0)
print_option("TCP_DEFER_ACCEPT (Defer Accept)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_DEFER_ACCEPT", strerror(errno));

/* TCP_SYNCNT: SYN retransmit count */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_SYNCNT, &val, &len) == 0)
print_option("TCP_SYNCNT (SYN Retries)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_SYNCNT", strerror(errno));

/* TCP_LINGER2: FIN_WAIT2 timeout */


if (getsockopt(sockfd, IPPROTO_TCP, TCP_LINGER2, &val, &len) == 0)
print_option("TCP_LINGER2 (FIN_WAIT2 Timeout)", val);
else
printf(" %-30s : Error (%s)\n", "TCP_LINGER2", strerror(errno));

/* TCP_INFO: Detailed TCP state info */


struct tcp_info ti;
socklen_t tilen = sizeof(ti);
if (getsockopt(sockfd, IPPROTO_TCP, TCP_INFO, &ti, &tilen) == 0) {
printf("\n --- TCP_INFO (Detailed State) ---\n");
printf(" %-30s : %u\n", " tcpi_state", ti.tcpi_state);
printf(" %-30s : %u\n", " tcpi_rto (us)", ti.tcpi_rto);
printf(" %-30s : %u\n", " tcpi_snd_mss", ti.tcpi_snd_mss);
printf(" %-30s : %u\n", " tcpi_rcv_mss", ti.tcpi_rcv_mss);
printf(" %-30s : %u\n", " tcpi_rtt (us)", ti.tcpi_rtt);
printf(" %-30s : %u\n", " tcpi_rttvar (us)", ti.tcpi_rttvar);
printf(" %-30s : %u\n", " tcpi_snd_cwnd", ti.tcpi_snd_cwnd);
printf(" %-30s : %u\n", " tcpi_snd_ssthresh", ti.tcpi_snd_ssthresh);
} else {
printf(" %-30s : Error (%s)\n", "TCP_INFO", strerror(errno));
}

printf("\n");
}

/* Print SOL_SOCKET level options */


void print_socket_options(int sockfd) {
int val;
socklen_t len = sizeof(val);
print_separator("SOCKET LEVEL OPTIONS (SOL_SOCKET)");

if (getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &val, &len) == 0)


print_option("SO_SNDBUF (Send Buffer Size)", val);

if (getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &val, &len) == 0)


print_option("SO_RCVBUF (Recv Buffer Size)", val);

if (getsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &val, &len) == 0)


print_option("SO_KEEPALIVE (Keepalive)", val);

if (getsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &val, &len) == 0)


print_option("SO_REUSEADDR (Reuse Address)", val);

if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &val, &len) == 0)


print_option("SO_ERROR (Pending Error)", val);

if (getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &val, &len) == 0) {


printf(" %-30s : %d (%s)\n", "SO_TYPE (Socket Type)", val,
val == SOCK_STREAM ? "SOCK_STREAM (TCP)" :
val == SOCK_DGRAM ? "SOCK_DGRAM (UDP)" : "Other");
}

printf("\n");
}

int main(void) {
int sockfd;

printf("\n");
printf("************************************************************\n");
printf("* TCP/IP Socket Options Display Program *\n");
printf("************************************************************\n");

/* Create a TCP socket */


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket() failed");
exit(EXIT_FAILURE);
}

printf("\n [+] TCP socket created successfully (fd = %d)\n", sockfd);

/* Print options at each layer */


print_socket_options(sockfd);
print_ip_options(sockfd);
print_tcp_options(sockfd);

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

$ # No external libraries required

Run
$ ./socket_options
OUTPUT ANALYSIS

Option Value Interpretation


IP_TTL 64 Default Linux TTL; packets drop after 64 hops
IP_TOS 0 Best-effort delivery; no special priority
IP_MULTICAST_TTL 1 Multicast traffic stays within local subnet
TCP_NODELAY 0 Nagle enabled; small packets are coalesced
TCP_MAXSEG 536 Conservative MSS before TCP handshake negotiation
TCP_KEEPIDLE 7200 s Keepalive probing starts after 2 hours of idle
TCP_KEEPINTVL 75 s 75 s between consecutive keepalive probes
TCP_KEEPCNT 9 Drop after 9 unanswered probes (~11 min)
TCP_SYNCNT 6 Six SYN retries before reporting connection failure
TCP_LINGER2 60 s FIN_WAIT2 state lasts up to 60 seconds
4. Exercises on Socket Programming using C and Java
4a) TCP CLIENT-SERVER PROGRAM IN C
Aim: To implement basic socket programming exercises using C and Java for client-server
communication and file transfer.

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

EXERCISE 4 (A): TCP Client-Server in C


Server Program (server.c)
// TCP Server in C
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define BUFSIZE 1024

int main() {
int server_fd, client_fd;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
char buffer[BUFSIZE];

server_fd = socket(AF_INET, SOCK_STREAM, 0);

addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(PORT);

bind(server_fd, (struct sockaddr*)&addr, sizeof(addr));


listen(server_fd, 5);

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);

printf("Client: %s", buffer);

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;
}

Client Program (client.c)


#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define BUFSIZE 1024

int main() {
int sockfd;
struct sockaddr_in addr;
char buffer[BUFSIZE];

sockfd = socket(AF_INET, SOCK_STREAM, 0);

addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
inet_pton(AF_INET, "[Link]", &addr.sin_addr);

connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));

printf("Connected to server\n");

while (1) {
printf("Client: ");
fgets(buffer, BUFSIZE, stdin);

send(sockfd, buffer, strlen(buffer), 0);

if (strncmp(buffer, "exit", 4) == 0)
break;
memset(buffer, 0, BUFSIZE);
recv(sockfd, buffer, BUFSIZE, 0);

printf("Server: %s", buffer);


}

close(sockfd);
return 0;
}

Output

Result
Thus, TCP client-server communication using C was successfully implemented.

4 (B): UDP Client–Server in C


To develop and execute a UDP Client–Server communication program in C using socket
programming, enabling the exchange of messages between a client and a server over the User
Datagram Protocol (UDP).
Theory
User Datagram Protocol (UDP) is a connectionless transport-layer protocol in the TCP/IP suite.
Unlike TCP, UDP does not establish a connection before transmitting data, making it faster
and more efficient for applications that require low latency. However, UDP does not guarantee
packet delivery, ordering, or error recovery.
In UDP communication, the server creates a socket, binds it to a specific port, and waits for
incoming datagrams from clients. The client creates a socket and sends messages directly to
the server's address and port using the sendto() function. The server receives messages using
recvfrom(), processes them, and can send responses back to the client.
The key socket programming functions used in this experiment are:
• socket() – Creates a UDP socket.
• bind() – Associates the server socket with an IP address and port number.
• sendto() – Sends data to a specified destination.
• recvfrom() – Receives data from a sender.
• close() – Closes the socket and releases resources.
In the given program:
1. The UDP server creates a socket and binds it to port 8080.
2. The server waits for messages from the client.
3. The UDP client creates a socket and sends messages to the server.
4. The server receives the messages and sends replies back.
5. Communication continues until either side sends the message "exit"

UDP SERVER (udp_server.c)

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define BUFSIZE 1024

int main() {
int sockfd;
char buffer[BUFSIZE];
struct sockaddr_in server_addr, client_addr;
socklen_t len = sizeof(client_addr);

// Create UDP socket


sockfd = socket(AF_INET, SOCK_DGRAM, 0);

// Configure server address


server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);

// Bind socket
bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));

printf("[UDP SERVER] Waiting for data...\n");

while (1) {
memset(buffer, 0, BUFSIZE);

recvfrom(sockfd, buffer, BUFSIZE, 0,


(struct sockaddr*)&client_addr, &len);

printf("[CLIENT] %s\n", buffer);

if (strncmp(buffer, "exit", 4) == 0)
break;

printf("[SERVER] Reply: ");


fgets(buffer, BUFSIZE, stdin);

sendto(sockfd, buffer, strlen(buffer), 0,


(struct sockaddr*)&client_addr, len);
}

close(sockfd);
return 0;
}

UDP CLIENT (udp_client.c)

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define BUFSIZE 1024

int main() {
int sockfd;
char buffer[BUFSIZE];
struct sockaddr_in server_addr;
socklen_t len = sizeof(server_addr);

// Create UDP socket


sockfd = socket(AF_INET, SOCK_DGRAM, 0);

// Configure server address


server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY; // localhost

printf("[UDP CLIENT] Started\n");

while (1) {
printf("[CLIENT] Message: ");
fgets(buffer, BUFSIZE, stdin);

sendto(sockfd, buffer, strlen(buffer), 0,


(struct sockaddr*)&server_addr, len);
if (strncmp(buffer, "exit", 4) == 0)
break;

memset(buffer, 0, BUFSIZE);

recvfrom(sockfd, buffer, BUFSIZE, 0,


(struct sockaddr*)&server_addr, &len);

printf("[SERVER] %s", buffer);


}

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.

EXERCISE 4 (C): TCP Client–Server in Java

TCP SERVER ([Link])

import [Link].*;
import [Link].*;

public class Server {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5000);
[Link]("[SERVER] Waiting for client...");

Socket socket = [Link]();


[Link]("[SERVER] Client connected");

DataInputStream in = new DataInputStream([Link]());


DataOutputStream out = new DataOutputStream([Link]());

String message;

while (true) {
message = [Link]();
[Link]("[CLIENT] " + message);

if ([Link]("exit"))
break;

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));


[Link]("[SERVER] Reply: ");
String reply = [Link]();

[Link](reply);
[Link]();
}

[Link]();
[Link]();
[Link]("[SERVER] Connection closed");

} catch (Exception e) {
[Link](e);
}
}
}

TCP CLIENT ([Link])


import [Link].*;
import [Link].*;

public class Client {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5000);
[Link]("[CLIENT] Connected to server");

DataInputStream in = new DataInputStream([Link]());


DataOutputStream out = new DataOutputStream([Link]());

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

String message;

while (true) {
[Link]("[CLIENT] Message: ");
message = [Link]();

[Link](message);
[Link]();

if ([Link]("exit"))
break;

String response = [Link]();


[Link]("[SERVER] " + response);
}

[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

EXERCISE 4 (D): File Transfer using Java Sockets

FILE SERVER ([Link])


import [Link].*;
import [Link].*;

public class FileServer {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(6000);
[Link]("[SERVER] Waiting for client...");

Socket socket = [Link]();


[Link]("[SERVER] Client connected");

InputStream in = [Link]();
FileOutputStream fos = new FileOutputStream("[Link]");

byte[] buffer = new byte[1024];


int bytesRead;

while ((bytesRead = [Link](buffer)) != -1) {


[Link](buffer, 0, bytesRead);
}

[Link]("[SERVER] File received successfully");


[Link]();
[Link]();
[Link]();

} catch (Exception e) {
[Link](e);
}
}
}

FILE CLIENT ([Link])


import [Link].*;
import [Link].*;

public class FileClient {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 6000);
[Link]("[CLIENT] Connected to server");

FileInputStream fis = new FileInputStream("[Link]");


OutputStream out = [Link]();

byte[] buffer = new byte[1024];


int bytesRead;

while ((bytesRead = [Link](buffer)) != -1) {


[Link](buffer, 0, bytesRead);
}

[Link]("[CLIENT] File sent successfully");

[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]

5a. Setting up of various network topologies

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)

Experiment Procedure (NS-3)

1. Star Topology

Step 1: Install NS-3


Follow the WSL2 + Ubuntu installation method. Once installed, verify:
cd ns-3-dev
./ns3 run hello-simulator
If it runs successfully, you're ready.

Step 2: Create a New Simulation File


Create a file:
mkdir -p scratch
nano scratch/[Link]
Type the following code:
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/mobility-module.h"
#include "ns3/netanim-module.h"
using namespace ns3;

int main()
{
NodeContainer nodes;
[Link](5);

CsmaHelper csma;
[Link]("DataRate", StringValue("100Mbps"));
[Link]("Delay", TimeValue(MilliSeconds(2)));

NetDeviceContainer devices = [Link](nodes);

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]

set tracefile [open [Link] w]


$ns trace-all $tracefile

set namfile [open [Link] w]

# Wireless NAM trace


$ns namtrace-all-wireless $namfile 500 500

set topo [new Topography]


$topo load_flatgrid 500 500

create-god 3

$ns node-config -adhocRouting DSDV \


-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail \
-ifqLen 50 \
-antType Antenna/OmniAntenna \
-propType Propagation/TwoRayGround \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON

# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]

# Node positions
$n0 set X_ 50
$n0 set Y_ 50

$n1 set X_ 150


$n1 set Y_ 150

$n2 set X_ 250


$n2 set Y_ 250

# Traffic
set tcp [new Agent/TCP]
set sink [new Agent/TCPSink]

$ns attach-agent $n0 $tcp


$ns attach-agent $n2 $sink

$ns connect $tcp $sink

set ftp [new Application/FTP]


$ftp attach-agent $tcp

$ns at 1.0 "$ftp start"


$ns at 10.0 "finish"

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

5c. Measurement of Routing Protocols in NS2


Aim: To simulate and compare different routing protocols in NS2 and measure their
performance using trace file analysis.

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

NS2 IMPLEMENTATION: nano [Link]

set ns [new Simulator]

set tracefile [open [Link] w]


$ns trace-all $tracefile

set namfile [open [Link] w]


$ns namtrace-all-wireless $namfile 500 500

set topo [new Topography]


$topo load_flatgrid 500 500

create-god 4

$ns node-config -adhocRouting AODV \


-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail \
-ifqLen 50 \
-antType Antenna/OmniAntenna \
-propType Propagation/TwoRayGround \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON
# Nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

$n0 set X_ 50; $n0 set Y_ 50


$n1 set X_ 150; $n1 set Y_ 150
$n2 set X_ 250; $n2 set Y_ 250
$n3 set X_ 300; $n3 set Y_ 300

# TCP connection
set tcp [new Agent/TCP]
set sink [new Agent/TCPSink]

$ns attach-agent $n0 $tcp


$ns attach-agent $n3 $sink
$ns connect $tcp $sink

set ftp [new Application/FTP]


$ftp attach-agent $tcp

$ns at 1.0 "$ftp start"


$ns at 10.0 "finish"

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]

Packet Received: grep -c "^r" [Link]

Packet Loss: grep -c "^d" [Link]


Packet Delivery Ratio (PDR):
awk '
$1=="r"{recv++}
$1=="+"{send++}
END{
print "PDR =", (recv/send)*100, "%"
}' [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.

5d. Analysis of TCP/IP Protocol Under Various Mechanisms in NS2

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

c. TCP Mechanisms in NS2


• Slow Start
• Congestion Avoidance
• Fast Retransmit
• Fast Recovery

NS2 IMPLEMENTATION (TCP Simulation)

set ns [new Simulator]

set tf [open [Link] w]


$ns trace-all $tf

set nf [open [Link] w]


$ns namtrace-all $nf

# Create nodes
set n0 [$ns node]
set n1 [$ns node]

# Wired duplex link


$ns duplex-link $n0 $n1 1Mb 10ms DropTail

# TCP Agent
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp

# TCP Sink
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink

$ns connect $tcp $sink

# FTP Traffic
set ftp [new Application/FTP]
$ftp attach-agent $tcp

$ns at 1.0 "$ftp start"


$ns at 8.0 "$ftp stop"
$ns at 9.0 "finish"

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.

5e. Setting Up a Network Carrying Various Application Protocols and Analyzing


Performance
Aim: To set up a network in NS2 that carries different application protocols (FTP over TCP
and CBR over UDP) and analyze their performance using trace files.

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

set nf [open [Link] w]


$ns namtrace-all $nf

# 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

# FTP over TCP


set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n3 $sink

$ns connect $tcp $sink

set ftp [new Application/FTP]


$ftp attach-agent $tcp

# CBR over UDP


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp

set null [new Agent/Null]


$ns attach-agent $n2 $null

$ns connect $udp $null

set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp
$cbr set packetSize_ 500
$cbr set interval_ 0.05

# Schedule traffic
$ns at 1.0 "$ftp start"
$ns at 2.0 "$cbr start"

$ns at 8.0 "$ftp stop"


$ns at 8.0 "$cbr stop"

$ns at 9.0 "finish"

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];

sockfd = socket(AF_INET, SOCK_STREAM, 0);

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;
}

C. TCP Socket Client


#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

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

ANALYSIS – WHICH IS BEST?


For Same-System Communication
Pipe is best
Reasons:
• Fastest communication
• Minimal overhead
• Easy implementation
• Low memory usage

For Client-Server Applications


Socket is best
Reasons:
• Supports network communication
• Flexible architecture
• Supports multiple clients

For Internet Communication


TCP/IP is best
Reasons:
• Reliable transmission
• Congestion control
• Error recovery
• Global network support

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.

You might also like