1) Implement daytime client/server program using TCP sockets in python.
# Daytime Server (TCP) in Jupyter Notebook
import socket
from datetime import datetime
import threading
HOST = '[Link]' # Localhost
PORT = 13000 # Port for Daytime service
def start_daytime_server():
with [Link](socket.AF_INET, socket.SOCK_STREAM) as s:
[Link]((HOST, PORT))
[Link](1)
print(f"Daytime server running on {HOST}:{PORT}")
while True:
conn, addr = [Link]()
with conn:
print(f"Connected by {addr}")
current_time = [Link]().strftime('%Y-%m-%d %H:%M:%S')
[Link](current_time.encode())
# Start the server in a background thread so it doesn't block the notebook
server_thread = [Link](target=start_daytime_server, daemon=True)
server_thread.start()
# Daytime Client (TCP) in Jupyter Notebook
import socket
HOST = '[Link]' # Server IP
PORT = 13000 # Server Port
def get_daytime():
with [Link](socket.AF_INET, socket.SOCK_STREAM) as s:
[Link]((HOST, PORT))
data = [Link](1024)
print("Received from server:", [Link]())
# Call the client function
get_daytime()
OUTPUT:
Server side:
Daytime server running on [Link]:13000
Client_side:
Received from server: 2025-07-16 18:44:33
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 messa
ge. Client program should print the results appropriately.
# SERVER SIDE [Link]
# TCP Server in Jupyter Notebook (Threaded)
import socket
import threading
HOST = '[Link]'
PORT = 14000
def handle_client(conn, addr):
print(f"Connected by {addr}")
data = [Link](1024).decode()
nums = list(map(float, [Link]().split(',')))
if len(nums) == 3:
a, b, c = nums
total = a + b + c
diff = a - b - c
prod = a * b * c
result = f"Sum: {total}, Difference: {diff}, Product: {prod}"
else:
result = "Error: Please send exactly 3 numbers."
[Link]([Link]())
[Link]()
def start_server():
with [Link](socket.AF_INET, socket.SOCK_STREAM) as s:
[Link]((HOST, PORT))
[Link]()
print(f"Server listening on {HOST}:{PORT}")
while True:
conn, addr = [Link]()
client_thread = [Link](target=handle_client, args=(conn, addr))
client_thread.start()
# Run server in background thread
server_thread = [Link](target=start_server, daemon=True)
server_thread.start()
# CLIENT SIDE [Link]
# TCP Client in Jupyter Notebook
import socket
HOST = '[Link]'
PORT = 14000
def send_numbers_and_receive_results(a, b, c):
message = f"{a},{b},{c}"
with [Link](socket.AF_INET, socket.SOCK_STREAM) as s:
[Link]((HOST, PORT))
[Link]([Link]())
data = [Link](1024).decode()
print("Server Response:", data)
# Example call
send_numbers_and_receive_results(10, 5, 2)
OUTPUT:
Server side:
Server listening on [Link]:14000
Client side:
Server Response: Sum: 17.0, Difference: 3.0, Product: 100.0
3) Python program that prints the IP layer and TCP layer socket options in a separate f
ile.
import socket
import os
# Dictionary of common IP and TCP socket options
socket_options = {
socket.SOL_SOCKET: {
"SO_REUSEADDR": socket.SO_REUSEADDR,
"SO_KEEPALIVE": socket.SO_KEEPALIVE,
"SO_BROADCAST": socket.SO_BROADCAST,
"SO_RCVBUF": socket.SO_RCVBUF,
"SO_SNDBUF": socket.SO_SNDBUF
},
socket.IPPROTO_TCP: {
"TCP_NODELAY": socket.TCP_NODELAY,
"TCP_MAXSEG": socket.TCP_MAXSEG,
}
}
# Output file path
output_file = "socket_options.txt"
# Create TCP socket
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Collect options info
results = []
for level, opts in socket_options.items():
level_name = "SOL_SOCKET" if level == socket.SOL_SOCKET else "IPPROTO_TCP"
[Link](f"\n[{level_name} options]")
for opt_name, opt_value in [Link]():
try:
val = [Link](level, opt_value)
[Link](f"{opt_name} = {val}")
except OSError as e:
[Link](f"{opt_name} = Error: {e}")
# Close socket
[Link]()
# Write to file
with open(output_file, "w") as f:
[Link]("\n".join(results))
# Print to notebook
print("Socket Options:\n")
print("\n".join(results))
print(f"\nSocket options written to: {[Link](output_file)}")
OUTPUT:
Socket Options:
[SOL_SOCKET options]
SO_REUSEADDR = 0
SO_KEEPALIVE = 0
SO_BROADCAST = Error: [WinError 10042] An unknown, invalid, or unsupported option or level was
specified in a getsockopt or setsockopt call
SO_RCVBUF = 65536
SO_SNDBUF = 65536
[IPPROTO_TCP options]
TCP_NODELAY = 0
TCP_MAXSEG = Error: [WinError 10042] An unknown, invalid, or unsupported option or level was s
pecified in a getsockopt or setsockopt call
Socket options written to: C:\Users\Admin\NETWROK_PROGRAMMING_LAB\P3\socket_options.txt
4) Python program to Demonstrate TCP Echo Server and Client.
server_echo.ipynb
import socket
import threading
def handle_client(conn, addr):
print(f"[CONNECTED] {addr}")
while True:
try:
data = [Link](1024)
if not data:
break
print(f"From {addr}: {[Link]()}")
# Echo back the received data
[Link](data)
except:
break
[Link]()
print(f"[DISCONNECTED] {addr}")
def start_echo_server():
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("[Link]", 5555)) # Localhost port 5555
[Link]()
print("[SERVER STARTED] Listening on port 5555...")
while True:
conn, addr = [Link]()
[Link](target=handle_client, args=(conn, addr), daemon=True).start()
# Start server in a background thread so Jupyter won't block
[Link](target=start_echo_server, daemon=True).start()
client_echo.ipynb
import socket
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("[Link]", 5555))
while True:
msg = input("You: ")
if [Link]() == "exit":
break
[Link]([Link]())
data = [Link](1024).decode()
print(f"Echo from server: {data}")
[Link]()
OUTPUT:
Server side:
Client side:
5) Implement a server that listens on a port and echoes back any message received from
the client in java.
File name: [Link]
// [Link]
import [Link].*;
import [Link].*;
public class EchoServer {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
[Link]("Echo server started on port " + port);
while (true) {
Socket clientSocket = [Link]();
[Link]("Client connected: " + [Link]());
// Setup input/output streams
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
String received;
while ((received = [Link]()) != null) {
[Link]("Received: " + received);
[Link]("Echo: " + received);
}
[Link]();
[Link]("Client disconnected.");
}
} catch (IOException e) {
[Link]();
}
}
}
File Name: [Link]
// [Link]
import [Link].*;
import [Link].*;
public class EchoClient {
public static void main(String[] args) {
String host = "localhost";
int port = 12345;
try (Socket socket = new Socket(host, port);
BufferedReader userInput = new BufferedReader(new InputStreamReader([Link]));
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true)) {
[Link]("Connected to server. Type messages (type 'exit' to quit):");
String input;
while ((input = [Link]()) != null) {
if ([Link]("exit")) break;
[Link](input); // Send to server
String response = [Link](); // Read echo
[Link](response);
}
} catch (IOException e) {
[Link]();
}
}
}
OUTPUT:
Server side:
Client side:
3) Python program that prints the IP layer and TCP layer socket options in a separate
file.
socket_options.ipynb
import socket
def save_socket_options():
# Create a TCP socket for testing
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Define IP layer options
ip_options = {
"IP_TOS": socket.IP_TOS,
"IP_TTL": socket.IP_TTL,
"IP_MULTICAST_TTL": socket.IP_MULTICAST_TTL,
"IP_MULTICAST_LOOP": socket.IP_MULTICAST_LOOP,
}
# Define TCP layer options
tcp_options = {
"TCP_NODELAY": socket.TCP_NODELAY,
"TCP_MAXSEG": socket.TCP_MAXSEG,
}
# Save IP options with their current values
with open("ip_options.txt", "w") as f:
[Link]("=== IP Layer Socket Options (with values) ===\n")
for opt, val in ip_options.items():
try:
option_value = [Link](socket.IPPROTO_IP, val)
except OSError:
option_value = "Not supported on this system"
[Link](f"{opt} : {option_value}\n")
# Save TCP options with their current values
with open("tcp_options.txt", "w") as f:
[Link]("=== TCP Layer Socket Options (with values) ===\n")
for opt, val in tcp_options.items():
try:
option_value = [Link](socket.IPPROTO_TCP, val)
except OSError:
option_value = "Not supported on this system"
[Link](f"{opt} : {option_value}\n")
[Link]()
print("Options written to ip_options.txt and tcp_options.txt")
# Run in Jupyter
save_socket_options()
OUTPUT:
Options written to ip_options.txt and tcp_options.txt
tcp_options.txt
=== TCP Layer Socket Options (with values) ===
TCP_NODELAY : 0
TCP_MAXSEG : Not supported on this system
ip_options.txt
=== IP Layer Socket Options (with values) ===
IP_TOS : 0
IP_TTL : 128
IP_MULTICAST_TTL : Not supported on this system
IP_MULTICAST_LOOP : Not supported on this system