0% found this document useful (0 votes)
9 views23 pages

Merged

The document outlines various experiments involving socket programming, network topologies, and command-line utilities. It includes instructions for creating an HTTP server for file uploads and downloads, implementing a star topology in Cisco Packet Tracer, and simulating PING and TRACEROUTE commands. Additionally, it discusses applications using TCP sockets such as echo clients, chat applications, and file transfer, along with common networking commands like ping, nslookup, and netstat.

Uploaded by

Tushar Rajput
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)
9 views23 pages

Merged

The document outlines various experiments involving socket programming, network topologies, and command-line utilities. It includes instructions for creating an HTTP server for file uploads and downloads, implementing a star topology in Cisco Packet Tracer, and simulating PING and TRACEROUTE commands. Additionally, it discusses applications using TCP sockets such as echo clients, chat applications, and file transfer, along with common networking commands like ping, nslookup, and netstat.

Uploaded by

Tushar Rajput
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/ 23

Experiment No.

5
Create a socket for HTTP for web page upload and
download
Algorithm:

Step 1: Start the Server:


- Import the socket module.
- Create a TCP socket using socket.socket().
- Bind the socket to localhost and port (e.g., 8080).
- Start listening for client connections.

Step 2: Accept Client Connection:


- Accept an incoming client using accept().

Step 3: Receive HTTP Request:


- Use recv() to read the HTTP request from the client.
- Decode the received bytes to a string.

Step 4: Process the Request:


- If the request method is GET:
- If the URL is /, send index.html containing the file
upload form.
- If the URL is /uploads/<filename>, locate and send
the file content.
- If the request method is POST:
- Parse the multipart form data.
- Extract and save the uploaded file to a folder.
Step 5: Send HTTP Response:
- Send appropriate HTTP headers and content:
- 200 OK for success.
- 404 Not Found if file is missing.
- Include confirmation messages or downloadable files.
Step 6: Close Connection:
- Close the connection after response is sent.
Step 7: Repeat:
- Keep the server running and continue handling new
requests.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Upload File</title>
</head>
<body>
<h2>Upload a file</h2>
<form method="POST" enctype="multipart/form-data" action="/">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>

Program in Python:
import socket
import os
HOST, PORT = '', 8080
UPLOAD_DIR = 'uploads'
if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR)
def handle_request(conn):
request = conn.recv(1024 * 100).decode(errors='ignore')
lines = request.split("\r\n")
method = lines[0].split()[0]
if method == "GET":
if lines[0].startswith("GET / "):
with open("index.html", "rb") as f:
content = f.read()
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
+content)
elif lines[0].startswith("GET /uploads/"):
filename = lines[0].split()[1].replace("/uploads/", "")
filepath = os.path.join(UPLOAD_DIR, filename)
if os.path.exists(filepath):
with open(filepath, "rb") as f:
content = f.read()
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/
octet-stream\r\n\r\n" + content)
else:
conn.sendall(b"HTTP/1.1 404 Not Found\r\n\r\nFile not found.")
else:
conn.sendall(b"HTTP/1.1 404 Not Found\r\n\r\nPage not found.")

elif method == "POST":


# Very basic multipart parser
boundary = request.split("boundary=")[1].split("\r\n")[0]
parts = request.split(boundary)
for part in parts:
if "filename=" in part:
header, filedata = part.split("\r\n\r\n", 1)
filename = header.split("filename=")[1].split("\"")[1]
filedata = filedata.rsplit("\r\n", 1)[0]
with open(os.path.join(UPLOAD_DIR, filename), "wb") as f:
f.write(filedata.encode())
response = f"<html><body><h2>File '{filename}' uploaded
successfully.</h2><a href='/'>Go back</a></body>
</html>"
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type:
text/html\r\n\r\n" + response.encode())
break

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:


s.bind((HOST, PORT))
s.listen(5)
print(f"[*] Listening on http://localhost:{PORT}")
while True:
conn, addr = s.accept()
with conn:
handle_request(conn)
Experiment No. 6
Implementing Star Topology using Cisco Packet Tracer.

Star Topology is one of the most common network topologies used in


computer networks. In this setup, all the devices (nodes) are
individually connected to a central device like a switch or hub using
separate cables. The central device acts as a mediator to transmit data
between nodes.
Advantages:

1. Robust
2. Less expensive
3. Very reliable
4. Easy fault detection

Disadvantages:

1. If even one hub goes down, everything goes down


2. Extra hardware like switches or hubs required makes it little
more expensive
3. If network device fails, all the connected devices fails.
4. Hub requires more resources

Command:

"pingip_address_of_any_device"

Example:

ping 192.168.1.4

Note: If the connections are correct Then you will receive the
response.
Experiment No. 7
Write a code simulating PING command and Trace route command.

Cisco Packet Tracer: How to Simulate PING & TRACEROUTE


1. Setting Up the Network in Packet Tracer
1. Add three PCs (PCI, PC2, PC3).
2. Connect them via a Switch.
3. Assign IPs:
 PCI: 192.168.1.1
 PC2: 192.168.1.2
 PC3: 192.168.1.3
4. Use the CLI to send PING and Traceroute commands.
2. Running PING in Packet Tracer
On PC1, open the CLI and type:
ping 192.168.1.2
If successful, you'll see:
Reply from 192.168.1.2: bytes=32 time<1ms TTL=128
3. Running TRACEROUTE in Packet Tracer
tracert 192.168.1.3

Program:

#include <stdio.h>
helude <stdlib.h>
void ping(char *ip)
{
char command[50];
sprintf(command. "ping -c 4 "%s", ip);
//Linux/Mac (Use "-n 4" for Windows)
system(command);
}
void traceroute(char *ip)
{
char command[50];
sprintf(command, "traceroute %s", ip);
// Use "tracert" for Windows
system(command);
}
int main()
{
int choice;
char ip[20];
while (1)
{
printf("\n--- PING & TRACEROUTE SIMULATOR ---\n");
printf("1. PING a Host\n");
printf("2, TRACEROUTE to a Host\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice 3) break;
printf("Enter IP Address or Domain: ");
scanf("%s", ip);
switch (choice)
{
case 1:
ping(ip);
break:
case 2:
traceroute(ip);
break;
default:
printf("Invalid choice! Try again.\n");
}
}
return 0;

OUTPUT:
--- PING & TRACEROUTE SIMULATOR ---
1. PING a Host
2. TRACEROUTE to a Host
3. Exit
Enter your choice: 1
Enter IP Address or Domain: google.com

Pinging google.com with 32 bytes of data: Reply from 142.250.74.174:


bytes=32 time=12ms TTL=114
Experiment No. 8
Program-8: Applications using TCP Sockets like

a. Echo client and echo server


b. Chat
c. File Transfer

TCP sockets are widely used for communication between networked devices.
Below are three commonly implemented applications:
1. Echo Client and Echo Server - The client sends a message, and the
server echoes it back.
2. Chat Application - Multiple clients can chat via a central server.
3. File Transfer - A client sends a file to the server, which saves it.
1. Echo Client and Echo Server (C Code)
Server Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main()
{
int server fd, new_socket;
struct sockaddr_in address;
char buffer[BUFFER_SIZE]={0};
int addrlen = sizeof(address);
// Create socket
server fd socket(AF_INET, SOCK_STREAM, 0);
address.sin_family AF_INET;
address.sin_addr.s addr INADDR_ANY:
address.sin_port = htons(PORT);
// Bind and listen
bind(server_fd, (struct sockaddr *)&address, sizeof(address));
listen(server_fd, 3);
printf("Echo server listening on port %d...\n", PORT);
// Accept connection
new socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t
*)&addrlen);
while (1)
{
memset(buffer, 0, BUFFER_SIZE);
read(new_socket, buffer, BUFFER_SIZE);
printf("Received: %s\n", buffer);
send(new_socket, buffer, strlen(buffer), 0);
}
close(server_fd);
return 0;
}

Client Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main()
{
int sock = 0;
struct sockaddr_in serv_addr,
char buffer[BUFFER_SIZE] = {0};
// Create socket
socksocket(AF_INET, SOCK STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons (PORT);
inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);
// Connect to server
connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
while (1)
{
printf("Enter message: ");
fgets(buffer, BUFFER SIZE, stdin); send(sock, buffer, strlen(buffer), 0);
memset(buffer, 0, BUFFER SIZE); read(sock, buffer, BUFFER SIZE);
printf("Echoed back: %s\n", buffer);
}
close(sock);
return 0;
}

2. Chat Application (Python Code)


Chat Server
import socket
import threading
clients=
def handle_client(client_socket):
while True:
try: msg = client_socket.recv(1024).decode()
print(msg)
for client in clients:
if client! client socket:
client.send(msg.encode())
except:
clients.remove(client_socket)
client_socket.close()
break
server socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 8080))
server.listen(5)
print("Chat server started on port 8080...")
while True:
client_socket, addr = server.accept()
clients.append(client_socket)
print(f"New connection: {addr)")
threading. Thread(target-handle_client, args=(client_socket,)).start()

Chat Client:
import socket
import threading
def receive_messages(client_socket):
while True:
try:
msgclient_socket.recv(1024).decode()
print(msg)
except:
break
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 8080))
threading.Thread(target-receive_messages, args (client,)).start()
while True:
msg = input("")
client.send(msg.encode())

3.File Transfer:
File Server
import socket
server socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 8080))
server.listen(1)
print("File server listening on port 8080...")
conn, addr server.accept()
with open("received_file.txt", "wb") as f:
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
print("File received successfully.")
conn.close()

File Client
import socket

client = socket.socket(socket.AF INET, socket.SOCK STREAM)


client.connect(("127.0.0.1", 8080))

with open("file_to_send.txt", "rb") as f:


client.sendfile(f)

print("File sent successfully.")


client.close()

Cisco Packet Tracer Implementation


Network Setup
To simulate TCP applications in Cisco Packet Tracer, follow these steps:

1. Add Two PCs (PC1 and PC2).


2. Connect the PCs using a Switch.
3. Assign IP Addresses:
o PC1: 192.168.1.1
o PC2: 192.168.1.2
4. Enable TCP Services:
o In PC2, open the Services tab→ Enable HTTP and FTP.

Running Commands
On PC1 (Command Prompt), test TCP communication using:

sh
CopyEdit
ping 192.168.1.2
telnet 192.168.1.2 80
ftp 192.168.1.2
Program 10
AIM: Running and using services/commands like ping, trace route, ns lookup, Arp, telnet, p, etc.
1. Ping Command:
The ping command is a networking u lity used to test the reach ability of a host on an Internet
Protocol (IP) network. It can be used to determine whether a specific IP address is accessible, and
also measures the round-trip me for messages sent from the local host to a remote host. In
addi on, Ping can provide informa on about the network routes and the amount of me required
to traverse them.

2. IP Configura on Command
IP Config is a command-line tool that is used to display the current IP address configura on of a
Windows machine. This includes the IP address, subnet mask, and default gateway.
3. Netstat
Netstat is a networking u lity that displays all ac ve network connec ons and their status. It can
iden fy which applica ons are using specific ports and is helpful for troubleshoo ng networking
issues.

4. Nslookup
Nslookup is a command-line networking tool used to query the Domain Name System (DNS) for
domain name or IP address mappings, as well as other DNS records. It operates in two modes:
interac ve and non-interac ve.
On Windows, Nslookup is included as part of the Microso networking tools. To use it, open the
Command Prompt and type nslookup followed by the domain name or IP address you want to
query.

5. Systeminfo
The SYSTEMINFO command provides detailed informa on about a system's hardware and so ware,
including processor data, boot configura on, Windows version, and more.

You might also like