Network Programming in Python: Mehmet Hadi Gunes
Network Programming in Python: Mehmet Hadi Gunes
Network Programming in Python: Mehmet Hadi Gunes
in Python
Mehmet Hadi Gunes
Modified from
• Steve Holden
• Dan Rubenstein
• DK Moon
Objectives
• Endpoint of a connection
– Identified by IP address and Port number
3 2 App D1
1
socket Dest.
3 2
1
socket D2
D3
Types of Sockets
• When sending “Hi!” and “Hope you’re well”
• TCP treats them as a single bytes stream
Bytes stream
l l e w …e p o H ! i H
• UDP treats them as separate messages
Hope you’re
Hi!
well
Types of Sockets (cont’d)
• Thus, TCP needs application-level message
boundary.
– By carrying length in application-level header
Bytes stream
l l e w … o H 16 ! i H 3
Client/Server Concepts
• Server opens a specific port
– The one associated with its service
– Then just waits for requests
– Server is the passive opener
• Clients get ephemeral ports
– Guaranteed unique, 1024 or greater
– Uses them to communicate with server
– Client is the active opener
A Socket-eye view of the Internet
cse.unr.edu
(134.197.20.22)
newworld.cs.umass.edu
(128.119.245.93)
cluster.cs.columbia.edu
(128.59.21.14, 128.59.16.7,
128.59.16.5, 128.59.16.4)
bind() bind()
recvfrom() sendto()
[blocked] recvfrom()
[blocked]
sendto()
SERVER CLIENT
Simple Connectionless Server
Note that the bind() argument is a two-element tuple of address and port number
Simple Connectionless Client
socket socket
Active 1 Active 2 19
TCP state diagram
Connection-Oriented Services
socket() Server Client
bind()
socket()
listen()
connect()
accept()
write()
[blocked]
read()
read() [blocked]
[blocked]
write()
When interaction is over, server
loops to accept a new connection
Connection-Oriented Server
from socket import socket, AF_INET,
SOCK_STREAM
s = socket(AF_INET, SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(5) # max queued connections
while True:
sock, addr = s.accept()
# use socket sock to communicate
# with client process
• gethostbyaddr(ipaddr)
• gethostbyname_ex(hostname)
– Returns (hostname, aliases, addresses)
• Hostname is canonical name
• Aliases is a list of other names
• Addresses is a list of IP address strings
Treating Sockets as Files
• makefile([mode[, bufsize]])
– Creates a file object that references the socket
– Makes it easier to program to handle data streams
• No need to assemble stream from buffers
Summary of Address Families
• socket.AF_UNIX
– Unix named pipe (NOT Windows…)
• socket.AF_INET
– Internet – IP version 4
– The basis of this class
• socket.AF_INET6
– Internet – IP version 6
– Rather more complicated …
Summary of Socket Types
• socket.SOCK_STREAM
– TCP, connection-oriented
• socket.SOCK_DGRAM
– UDP, connectionless
• socket.SOCK_RAW
– Gives access to subnetwork layer
• SOCK_RDM, SOCK_SEQPACKET
– Very rarely used
Timeout Capabilities