Network Programming in Python
Network Programming in Python
in Python
Steve Holden
Holden Web
LinuxWorld
January 20, 2004
Introductions
• Steve Holden
– Professional instructor
• TCP/IP
• Database
• Security topics
– Consultant
• Over thirty years as a programmer
– Author of Python Web Programming
• New Riders, 2002
PROTOCOL DATA
Upper layer
A Application
T Host-to-host
N Internetwork
DL CRC Subnetwork
Application
Telnet SSH SMTP FTP NFS DNS SNMP
TCP UDP Host-to-host
IP Internetwork
bind() bind()
recvfrom() sendto()
[blocked] recvfrom()
[blocked]
sendto()
SERVER CLIENT
Steve Holden - LinuxWorld, January 20, 2004
Simple Connectionless Server
from socket import socket, AF_INET, SOCK_DGRAM
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('127.0.0.1', 11111))
while 1: # nowadays, "while True"
data, addr = s.recvfrom(1024)
print "Connection from", addr
s.sendto(data.upper(), addr)
Note that the bind() argument is a two-element tuple of address and port number
listen()
connect()
accept()
write()
[blocked]
read()
read() [blocked]
[blocked]
write()
When interaction is over, server
loops to accept a new connection
Steve Holden - LinuxWorld, January 20, 2004
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 1:
sock, addr = s.accept()
# use socket sock to communicate
# with client process
• htonl(i), htons(i)
– 32-bit or 16-bit integer to network format
• ntohl(i), ntohs(i)
– 32-bit or 16-bit integer to host format
• inet_aton(ipstr), inet_ntoa(packed)
– Convert addresses between regular strings and
4-byte packed strings
• 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
accept()
[blocked]
Client connection
read()
becomes
myserver = SocketServer.ThreadingTCPServer(
myaddr, UCHandler)
or
myserver = SocketServer.ForkingTCPServer(
myaddr, UCHandler)
frad = "[email protected]"
toads = ["[email protected]",
"[email protected]",
"[email protected]"]
form = cgi.FieldStorage()
vlist = []
for f in fields:
vlist.append("%s=%s" % (f, form.getfirst(f)))
<html><head><title>Hello!</title></head>
%s
</body></html>
""" % "<br>".join(vlist)
Get in touch: