A simple introduction to network programming using Python 3 socket module. This material was used in a 2-day summer training at Mansoura University in August 2016.
The examples included come from other tutorials with some changes. The source code of these and other examples can be found here:
https://github.com/ksonbol/socket_examples
3. Sockets
● The endpoints of a network connection
● Each host has a unique IP address
● Each service runs on a specific port
● Each connection is maintained on both
ends by a socket
● Sockets API allows us to send and receive
data
● Programming Languages provide modules
and classes to use this API
4. Socket Types
● Stream Sockets (SOCK_STREAM):
○ Connection-oriented
○ Use TCP
● Datagram Sockets (SOCK_DGRAM):
○ Connectionless
○ Use UDP
● Other types:
○ E.g. Raw Sockets
● We will use stream sockets
5. Python socket module
● socket.socket(family, type, proto)
○ Create new socket object
● socket.SOCK_STREAM (default)
● socket.SOCK_DGRAM
● socket.gethostname()
○ returns a string containing host name of the machine
● socket.gethostbyname(hostname)
○ Translates hostname to ip address
● socket.gethostbyaddr(ip_address)
○ Translates ip address to host name
7. Socket Object Methods (Server)
● socket.bind(address)
○ e.g. socket.bind((host, port))
● socket.listen(backlog)
○ backlog specifies wait queue size
○ e.g. socket.listen(5)
● socket.accept()
○ Blocks until a client makes a connection
○ Returns (conn, address) where conn is a new socket object usable to send and receive data
○ address is the address bound to the socket on the other end of the connection
8. Socket Object Methods
● socket.connect(address) - used by client
○ e.g. socket.connect((host, port))
● socket.send(bytes, flags)
○ e.g. socket.send(b‘Hello, World!’)
● socket.recv(bufsize, flags)
○ e.g. socket.recv(1024)
○ bufsize specify maximum amount of data in bytes to be received at once
● socket.close()
○ close connection
9. Example 1: Echo Server
# Echo server program
import socket
HOST = socket.gethostname()
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
10. Example 1: Echo Server
# Echo client program
import socket
HOST = 'localhost'
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))
11. Example 2: Basic Network Sniffer
#Packet sniffer in python
#For Linux
import socket
#create an INET, raw socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
# receive a packet
while True:
print s.recvfrom(65565)
Full Example with Packet Parsing
12. Example 3: File Transfer
# file_transfer_server.py
import socket
host = socket.gethostname()
port = 6000
s = socket.socket()
s.bind((host, port))
s.listen(5)
print('Server listening..')
...
13. Example 3: File Transfer
# file_transfer_server.py
...
while True:
conn, addr = s.accept()
print('New Connection from {}'.format(addr))
with open('test.txt', 'r') as f:
while True:
l = f.read(1024)
if not l: break
conn.send(l.encode())
print('Sent {}'.format(l))
print('Finished Sending.')
conn.close()
print('Connection closed')
14. Example 3: File Transfer
# file_transfer_client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = ‘localhost’ # Get local machine name
port = 6000 # Reserve a port for your service.
s.connect((host, port))
with open('received.txt', 'w') as f:
print('Downloading file..')
while True:
data = s.recv(1024)
if not data: break
f.write(data.decode())
print('Received: {}n'.format(data.decode()))
print('File downloaded successfully.')
s.close() # Close the socket when done
print('Connection closed')