Lab 3: Socket Programming

Back to Labs

1. Lab Introduction

Socket programming allows two programs to communicate over a network. Python provides the socket module to implement TCP/IP and UDP protocols. This lab demonstrates multiple client-server programs including chat, file transfer, arithmetic server, grading server, hostname resolution, and port scanning.

2. TCP Connection Process

Python also has libraries that provide higher-level access to application-level network protocols, such as FTP, HTTP, etc. TCP connection steps:

  1. STEP I: Server instantiates a ServerSocket with a port number.
  2. STEP II: Server calls accept() to wait for a client connection.
  3. STEP III: Client instantiates a Socket specifying server address and port.
  4. STEP IV: Socket attempts to connect to the server. If successful, a Socket object is ready.
  5. STEP V: Server accept() returns a socket connected to the client.

Data can now be sent bidirectionally using send/recv.

3. Important Socket Terms

  • Domain: Protocol family (AF_INET, PF_UNIX, etc.)
  • Type: Communication type: SOCK_STREAM (TCP) or SOCK_DGRAM (UDP)
  • Protocol: Usually 0, identifies protocol variant
  • Hostname: Network interface identifier

4. Additional Python Socket Programs

Examples with server and corresponding client code:


# TCP Server
import socket
s = socket.socket()
s.bind(('localhost', 9999))
s.listen(3)
print("Server hostname:", socket.gethostname())
while True:
    c, addr = s.accept()
    print("Connected with", addr)
    c.send(b"Welcome!\n")
    c.close()

# TCP Client
import socket
c = socket.socket()
c.connect(('localhost', 9999))
msg = c.recv(1024)
print(msg.decode())
c.close()
Simple TCP server sends a welcome message; client receives it.

# Server not needed; client resolves hostnames
import socket
hosts = ['www.google.com', 'www.facebook.com']
for h in hosts:
    print(f"{h}: {socket.gethostbyname(h)}")
Client resolves multiple hostnames using gethostbyname().

# Arithmetic TCP Server
import socket
s = socket.socket()
s.bind(('localhost', 9998))
s.listen(1)
c, addr = s.accept()
data = c.recv(1024).decode()
num1, num2, op = data.split()
num1, num2 = float(num1), float(num2)
ans = 0
if op == '+': ans = num1 + num2
elif op == '-': ans = num1 - num2
elif op == '*': ans = num1 * num2
elif op == '/': ans = num1 / num2
c.send(str(ans).encode())
c.close()
s.close()

# Arithmetic TCP Client
import socket
c = socket.socket()
c.connect(('localhost', 9998))
msg = input("Enter operation (e.g., 5 2 +): ")
c.send(msg.encode())
result = c.recv(1024).decode()
print("Result:", result)
c.close()
Question: Create a TCP-based Arithmetic Server and Client where the client sends two numbers and an operator, and the server returns the result.
Explanation: The server performs basic arithmetic operations (+, -, *, /) on numbers received from the client and returns the calculated result.

# Grading TCP Server
import socket
grades = [(4.33,"A+","Excellent"),(4.0,"A","Excellent"),(3.66,"A-","Very good")]
s=socket.socket()
s.bind(('localhost',9997))
s.listen(1)
c, addr=s.accept()
gp=float(c.recv(1024).decode())
for g, l, q in grades:
    if gp>=g:
        c.send(f"{l} ({q})".encode())
        break
c.close() 
s.close()

# Grading TCP Client
import socket
c=socket.socket()
c.connect(('localhost',9997))
gp=input("Enter GPA: ")
c.send(gp.encode())
grade=c.recv(1024).decode()
print("Grade:", grade)
c.close()
Question: Build a TCP Grading Server and Client where the client sends a GPA value, and the server responds with the corresponding letter grade and remark.
Explanation: The server compares the GPA with predefined grade boundaries and returns a message like "A (Excellent)" or "A- (Very Good)."

# File Receiver Server
import socket
s=socket.socket()
s.bind(('localhost',9995))
s.listen(1)
c, addr = s.accept()
filename=c.recv(1024).decode()
with open("recv_"+filename,'wb') as f:
    while True:
        data=c.recv(1024)
        if not data: 
        break
        f.write(data)
c.close()
s.close()

# File Sender Client
import socket
import os
c=socket.socket()
c.connect(('localhost',9995))
filename=input("File to send: ")
c.send(filename.encode())
with open(filename,'rb') as f:
    data=f.read(1024)
    while data:
        c.send(data)
        data=f.read(1024)
c.close()
Question: Implement a TCP-based File Transfer system where the client sends a file to the server.
Explanation: The client reads a file and transmits its contents to the server in chunks of 1024 bytes. The server receives and stores the file with a "recv_" prefix.

# Chat + File Server
import socket, os
s=socket.socket()
s.bind(('localhost',9999))
s.listen(1)
c, addr=s.accept()
while True:
    choice=c.recv(1024).decode()
    if choice=='1':
        msg=c.recv(1024).decode()
        if msg.lower()=='exit': break
        print("Client:",msg)
        reply=input("You: ")
        c.send(reply.encode())
    elif choice=='2':
        filename=c.recv(1024).decode()
        with open("recv_"+filename,'wb') as f:
            while True:
                data=c.recv(1024)
                if not data: 
                break
                f.write(data)
        break
    else: 
    break
c.close() 
s.close()

# Chat + File Client
import socket, os
c=socket.socket()
c.connect(('localhost',9999))
choice=input("1=Chat, 2=Send File: ")
c.send(choice.encode())
if choice=='1':
    while True:
        msg=input("You: ")
        c.send(msg.encode())
        if msg.lower()=='exit': break
        reply=c.recv(1024).decode()
        print("Server:",reply)
elif choice=='2':
    filename=input("File to send: ")
    c.send(filename.encode())
    with open(filename,'rb') as f:
        data=f.read(1024)
        while data:
            c.send(data)
            data=f.read(1024)
c.close()
Question: Combine chat and file transfer functionalities into a single TCP program where users can choose to either chat or send a file.
Explanation: The client first selects whether to start a chat session or send a file. Depending on the choice, the server either exchanges chat messages or receives a file.

5. Lab Resources

Lab 3 Task PDF

Download PDF