Merged
Merged
5
Create a socket for HTTP for web page upload and
download
Algorithm:
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.")
1. Robust
2. Less expensive
3. Very reliable
4. Easy fault detection
Disadvantages:
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.
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
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;
}
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
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.