0% found this document useful (0 votes)
3 views13 pages

Ds Final

The document is a practical file for a Distributed Systems course at Netaji Subhas University of Technology, detailing various programming assignments. It includes programs for creating network applications using sockets, implementing an FTP client, building a DNS server, and developing a chat server and client in Python. Each practical section contains the aim, code, and output for the respective programs.

Uploaded by

Ganesh Gaitonde
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)
3 views13 pages

Ds Final

The document is a practical file for a Distributed Systems course at Netaji Subhas University of Technology, detailing various programming assignments. It includes programs for creating network applications using sockets, implementing an FTP client, building a DNS server, and developing a chat server and client in Python. Each practical section contains the aim, code, and output for the respective programs.

Uploaded by

Ganesh Gaitonde
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
You are on page 1/ 13

Distributed Systems

Practical File
CICPE05

Netaji Subhas University of Technology,

East Campus, Geeta Colony,

New Delhi- 110031

Submitted To Submitted By
Mr. Arvind Kumar Rahul Shrivastava
2022UCI8067
CSIOT ( 3rd Year )
Index

Sno. Topic Date Signture


1. Write a program to create network
applications using sockets.
2. Write a program to implement FTP client.
3. Write a program to implement DNS server.
4. Write a program to build chat server and
client in Python using socket programming.

2
Practical 1

Aim : Write a program to create network applications using sockets.


Code :

Client.py

import socket

def client_program():
host = socket.gethostname() # Get the hostname of the server
port = 5000 # The same port as used by the server

client_socket = socket.socket() # Instantiate a socket object


client_socket.connect((host, port)) # Connect to the server

while True:
message = input("Type message (or 'q' to quit): ") # Take input from user
if message.lower() == 'q': # Exit if user types 'q'
break
client_socket.send(message.encode()) # Send message to server
data = client_socket.recv(1024).decode() # Receive response from server
print('Received from server: ' + data) # Print response

client_socket.close() # Close the connection

if __name__ == '__main__':
client_program()

Server.py
import socket

def server_program():
# Get the hostname
host = socket.gethostname()
port = 5000 # Initiate port number above 1024

server_socket = socket.socket() # Get instance


server_socket.bind((host, port)) # Bind host address and port together

# Configure how many clients the server can listen to simultaneously


server_socket.listen(2)
print("Server is listening...")

conn, address = server_socket.accept() # Accept new connection


print("Connection from: " + str(address))

while True:
# Receive data stream; it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data: # If data is not received, break

3
break
print("from connected user: " + str(data))
data = input(' -> ') # Take input from the server
conn.send(data.encode()) # Send data to the client

conn.close() # Close the connection

if __name__ == '__main__':
server_program()

Output :

4
Practical 2

Aim:Write a program to implement FTP client.

Code :

from pyftpdlib.authorizers import DummyAuthorizer


from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

# Define server parameters


FTP_PORT = 2121 # Port for the FTP server
FTP_USER = "gitalien" # Username for FTP access
FTP_PASSWORD = "admin" # Password for FTP access
FTP_DIRECTORY = "." # Directory for user access (current directory)

def main():
# Set up authorizer to manage permissions
authorizer = DummyAuthorizer()
authorizer.add_user(FTP_USER, FTP_PASSWORD, FTP_DIRECTORY, perm='elradfmw') # Full permissions for user

# Set up the FTP handler


handler = FTPHandler
handler.authorizer = authorizer

# Create and start the FTP server


address = ('', FTP_PORT) # Listen on all interfaces
server = FTPServer(address, handler)
print(f"FTP server started on port {FTP_PORT}.")
server.serve_forever() # Run the server indefinitely

if __name__ == '__main__':
main()

Output:

5
6
Practical 3

Aim : Write a program to implement DNS server.

Code:

from flask import Flask, render_template, request, redirect, url_for, flash


import sqlite3
import socket
import os

app = Flask(__name__)
app.secret_key = 'your_secret_key' # Required for flash messages

DB_NAME = 'websites.db'

def init_db():
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()

# Create the table if it doesn't exist


c.execute('''
CREATE TABLE IF NOT EXISTS websites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT UNIQUE,
dns TEXT
)
''')

# Check if 'category' column exists


c.execute("PRAGMA table_info(websites)")
columns = [col[1] for col in c.fetchall()]
if 'category' not in columns:
c.execute("ALTER TABLE websites ADD COLUMN category TEXT")
print(" 'category' column added to the websites table.")

# Update existing records with the correct category


c.execute("SELECT id, domain FROM websites WHERE category IS NULL")
for row in c.fetchall():
id, domain = row
category = get_category(domain)
c.execute("UPDATE websites SET category = ? WHERE id = ?", (category, id))
print(" Updated existing records with categories.")

conn.commit()
conn.close()

def get_local_dns(domain):
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()

7
c.execute("SELECT dns FROM websites WHERE domain = ?", (domain,))
result = c.fetchone()
conn.close()
return result[0] if result else None

def get_category(domain):
domain = domain.lower()
if domain.endswith('.in'):
return '.in'
elif domain.endswith('.com'):
return '.com'
elif domain.endswith('.org'):
return '.org'
else:
return 'other'

@app.route('/', methods=['GET', 'POST'])


def index():
if request.method == 'POST':
domain = request.form['domain']
local_dns = get_local_dns(domain)

if local_dns:
flash(f"DNS found locally for {domain}: {local_dns}", 'success')
else:
try:
ip = socket.gethostbyname(domain)
# Store the DNS record we just looked up
category = get_category(domain)
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
try:
c.execute("INSERT INTO websites (domain, dns, category) VALUES (?, ?, ?)",
(domain, ip, category))
conn.commit()
flash(f"DNS found globally for {domain}: {ip} - Added to database under {category} category",
'success')
except sqlite3.IntegrityError:
flash(f"DNS found globally for {domain}: {ip}", 'success')
finally:
conn.close()
except socket.gaierror:
flash(f"DNS not found for {domain}. You can register this website.", 'warning')

return redirect(url_for('index'))

# Fetch and categorize domains


conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute("SELECT domain, dns, category FROM websites")
rows = c.fetchall()
conn.close()

categorized = {
'.in': [],

8
'.com': [],
'.org': [],
'other': []
}

for row in rows:


domain, dns = row[0], row[1]
# Handle potential NULL category values
category = row[2] if row[2] else get_category(domain)

# Make sure we only use valid category keys


if category not in categorized:
category = 'other'

categorized[category].append((domain, dns))

return render_template('index.html', categorized=categorized)

@app.route('/register', methods=['POST'])
def register_website():
domain = request.form['domain']
dns = request.form['dns']
category = get_category(domain)

conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
try:
c.execute("INSERT INTO websites (domain, dns, category) VALUES (?, ?, ?)", (domain, dns, category))
conn.commit()
flash(f"Website {domain} registered successfully with DNS {dns} under {category} category.", 'success')
except sqlite3.IntegrityError:
flash(f"Domain {domain} is already registered", 'error')
finally:
conn.close()
return redirect(url_for('index'))

if __name__ == '__main__':
init_db()
app.run(debug=True)

9
Output :

10
Practical 4

Aim: Write a program to build chat server and client in Python using
socket programming.

Code:
Client.py

import socket
import threading

def main():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1' # localhost
port = 12345

try:
client_socket.connect((host, port))
print("Connected to server")
except socket.error as e:
print(f"Connection failed: {e}")
return

def receive_messages():
while True:
try:
data = client_socket.recv(1024)
if not data:
print("Server disconnected")
break
response = data.decode('utf-8')
print(f"Server response: {response}")
except ConnectionResetError:
print("Server disconnected unexpectedly")
break
client_socket.close()

receive_thread = threading.Thread(target=receive_messages)
receive_thread.daemon = True
receive_thread.start()

while True:
message = input("Enter your message: ")
try:
client_socket.sendall(message.encode('utf-8'))
except socket.error as e:
print(f"Error sending message: {e}")
break

if __name__ == "__main__":
main()

11
Server.py
import socket
import threading

def handle_client(client_socket, client_address):


print(f"Accepted connection from {client_address}")
while True:
try:
data = client_socket.recv(1024)
if not data:
print(f"Client {client_address} disconnected")
break
message = data.decode('utf-8')
print(f"Received message from {client_address}: {message}")
response = "Server received your message: " + message
client_socket.sendall(response.encode('utf-8'))
except ConnectionResetError:
print(f"Client {client_address} disconnected unexpectedly")
break
client_socket.close()

def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1' # localhost
port = 12345

try:
server_socket.bind((host, port))
except socket.error as e:
print(f"Bind failed: {e}")
return

server_socket.listen(5)
print(f"Server listening on {host}:{port}")

while True:
client_socket, client_address = server_socket.accept()
client_handler = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_handler.daemon = True
client_handler.start()

if __name__ == "__main__":
main()

Output:

12
13

You might also like