Nothing Special   »   [go: up one dir, main page]

Python Socket Programming

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42
At a glance
Powered by AI
The key takeaways from the document are that sockets are used for network programming in Python and allow applications to communicate over various protocols like TCP and UDP. TCP provides reliable, connection-oriented communication while UDP provides unreliable datagram-based transmission.

The two essential types of sockets are SOCK_STREAM, also known as TCP, which provides reliable delivery and guarantees in-order packets, and SOCK_DGRAM, also known as UDP, which provides unreliable delivery with no order guarantees.

The characteristics of UDP include that it is datagram-based, connectionless, unreliable, can broadcast, applications usually use message-based communication with no transport-layer retries, and processes are identified by port numbers.

Socket Programming

 A socket is a kind of file descriptor that is used


to refer to a network connection made between
the computer, often known as the client, and
any remote host.
 build client/server applications that
communicate using sockets
 Socket programming in python is somewhat
similar to file manipulation
 it is the concept of files and file descriptors
implemented in such a way that a connection is
considered to be a file.
 In order to use the socket functions, you must
import the socket module.
Python Basics 2-1
Socket programming
socket: door between application process and end-end-
transport protocol

application application
socket controlled by
process process app developer

transport transport
network network controlled
link
by OS
link Internet
physical physical

Python Basics 2-2


Creating a Socket
 Each layer uses the layer below
 The lower layer adds headers to the data from the
upper layer
 The data from the upper layer can also be a header
on data from the layer above …

Upper layer PROTOCOL DATA

Lower layer HDR DATA

Python Basics 2-3


UDP Characteristics
 Also datagram-based
 Connectionless, unreliable, can broadcast
 Applications usually message-based
 No transport-layer retries
 Applications handle (or ignore) errors
 Processes identified by port number
 Services live at specific ports
 Usually below 1024, requiring privilege

Python Basics 2-4


TCP Characteristics
 Connection-oriented
 Two endpoints of a virtual circuit
 Reliable
 Application needs no error checking
 Stream-based
 No predefined blocksize
 Processes identified by port numbers
 Services live at specific ports

Python Basics 2-5


Socket: Conceptual View

Python Basics 2-6


Two essential types of sockets
 SOCK_DGRAM
 SOCK_STREAM
 a.k.a. UDP
 a.k.a. TCP
 unreliable delivery
 reliable delivery
 no order guarantees
 in-order guaranteed
 no notion of “connection” – app
 connection-oriented indicates dest. for each packet
 bidirectional  can send or receive

App

3 2 App D1
1
socket Dest.
3 2
1
socket D2

D3
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

Python Basics 2-8


Connectionless Services

socket() socket()

bind() bind()

recvfrom() sendto()

[blocked] recvfrom()
[blocked]
sendto()

SERVER CLIENT
Python Basics 2-9
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 True:
data, addr = s.recvfrom(1024)
print "Connection from", addr
s.sendto(data.upper(), addr)

Python Basics 2-10


Simple Connectionless Client
from socket import
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('127.0.0.1', 0))
print "using", s.getsocketname()
server = ('127.0.0.1', 11111)
s.sendto("MixedCaseString", server)
data, addr = s.recvfrom(1024)
print "received", data, "from", addr
s.close()

Python Basics 2-11


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

Python Basics 2-12


Simple 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

 Client connection creates new socket


 Returned with address by accept()
 Server handles one client at a time

Python Basics 2-13


Simple Connection Oriented Client
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', data

 This is a simple example


 Sends message, receives response
 Server receives 0 bytes after close()

Python Basics 2-14


Creating a Socket
 The socket function from the socket module is
used to open a new socket in much the same
way that open() is used to open files.
 It takes two arguments: the socket family and
the socket type.
 Socket Families:
 AF_INET: IPv4 (you will probably use this)
 AF_INET6: IPv6
 AF_UNIX: unix domain
 Socket Types:
 SOCK_STREAM: TCP, used for reliable connections
 SOCK_DGRAM: UDP, used for games and utilities
 SOCK_RAW: a raw socket

Python Basics 2-15


Creating a Socket
import socket
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)

 Once a socket has been created, you have opened a


raw filed descriptor that python knows is intended to
represent a specific type of network connection
 Much like files, sockets are closed with the close()
function from the socket module.

Python Basics 2-16


Socket programming transport services:

Two socket types for two transport services:


 UDP: unreliable datagram
 TCP: reliable, byte stream-oriented

Application Example:
1. Client reads a line of characters (data) from its
keyboard and sends the data to the server.
2. The server receives the data and converts
characters to uppercase.
3. The server sends the modified data to the client.
4. The client receives the modified data and displays
the line on its screen.
Python Basics 2-17
Socket programming with UDP
UDP: no “connection” between client & server
 no handshaking before sending data
 sender explicitly attaches IP destination address and
port # to each packet
 rcvr extracts sender IP address and port# from
received packet
UDP: transmitted data may be lost or received
out-of-order
Application viewpoint:
 UDP provides unreliable transfer of groups of bytes
(“datagrams”) between client and server

Python Basics 2-18


Socket programming with UDP…
 When UDP is used, the server creates a socket and
binds address(es) and a port number to it.
 The server then waits for incoming data
(remember: UDP is connectionless).
 The clients also create a socket, then they bind it to
the appropriate interface
 The client sends data to the server, which awakes
from its blocked state and starts to compute its
response.
 sendto() is a function that sends packets to the
socket. It takes two tuples (serverName, Port)
 recvfrom(buflen) : Receive data from the socket,
up to buflen bytes, returning also the remote host
and port from which the data came Python Basics 2-19
Client/server socket interaction: UDP

server (running on serverIP) client


create socket:
create socket, port= x: clientSocket =
serverSocket = socket(AF_INET,SOCK_DGRAM)
socket(AF_INET,SOCK_DGRAM)
Create datagram with server IP and
port=x; send datagram via
read datagram from clientSocket
serverSocket

write reply to
serverSocket read datagram from
specifying clientSocket
client address,
port number close
clientSocket

Python Basics 2-202-20


Application
Example app: UDP client
Python UDPClient
include Python’s socket
library from socket import *
serverName = ‘127.0.0.1’
serverPort = 12000
create UDP socket for clientSocket = socket(AF_INET, SOCK_DGRAM)
server

get user keyboard


message = raw_input(’Input lowercase sentence:’)
input clientSocket.sendto(message,(serverName, serverPort))
Attach server name, port to
message; send into socket modifiedMessage, serverAddress =
read reply characters from clientSocket.recvfrom(2048)
socket into string
print modifiedMessage
print out received string clientSocket.close()
and close socket

Python Basics 2-21


Example app: UDP server
Python UDPServer
from socket import *
serverPort = 12000
create UDP socket serverSocket = socket(AF_INET, SOCK_DGRAM)
bind socket to local port
number 12000
serverSocket.bind(('', serverPort))
print “The server is ready to receive”
loop forever while 1:
Read from UDP socket into message, clientAddress = serverSocket.recvfrom(2048)
message, getting client’s
address (client IP and port) modifiedMessage = message.upper()
send upper case string serverSocket.sendto(modifiedMessage, clientAddress)
back to this client

Python Basics 2-22


Socket programming with TCP
client must contact server  when contacted by client,
 server process must first be server TCP creates new socket
running for server process to
 server must have created communicate with that
socket (door) that welcomes particular client
client’s contact  allows server to talk with
multiple clients
client contacts server by:  source port numbers used
 Creating TCP socket, to distinguish clients
specifying IP address, port (more in Chap 3)
number of server process
 when client creates socket: application viewpoint:
client TCP establishes TCP provides reliable, in-order
connection to server TCP byte-stream transfer (“pipe”)
between client and server

Python Basics 2-23


Connecting a Socket
 After socket is created, it is necessary to connect the
socket to a remote host. This is done with the connect()
function on the client side.
 The connect() function takes two arguments
 the hostname in string form, and a port number to connect to in
integer form.
import socket
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.connect(("amu.edu.et", 123))
 If you are the client of your connection, you need
not worry about Binding and Accepting, and can
move on to Sending and Receiving.

Python Basics 24
Binding and Accepting
 This is only relevant if your socket is intended to
be a server.
Binding
 If you are planning to accept incoming
connections, you must bind your socket.
 Whereas connecting forms a connection with a
remote socket,
 binding tells your socket that it should use a
specific port when looking for incoming
connections.

Python Basics 25
Binding and Accepting…
 You bind a socket using the bind() function,
which takes 2 arguments:
 the hostname that you wish to bind to, and the
port you wish to bind to.
 In general, the hostname will be your hostname,
so you can use the gethostbyname() function
from the socket module as the hostname
argument.
 Once it is bound to your hostname and to a
specific port, the socket knows that when told to
listen, it should listen at that port.

Python Basics 26
Binding and Accepting…
import socket
server = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server.bind(socket.gethostbyname(), 123) or
server.bind(“”, 31337) or
Listening
 Once the socket is bound to a port, you must tell
it to listen at that port.
 Listening; refers to monitoring a port so that it
can handle anything that tries to connect to that
port.

Python Basics 27
Binding and Accepting…
 The listen() function does this, listening to
connection attempts.
 It takes one argument, an integer value
representing the maximum number of queued
connection attempts to hold before dropping
older ones.
import socket
server = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server.bind(“”, 123)
server.listen(1) #listen at port 123 and queue only 1
connection at a time
 After a connection is made, it must be accepted.
Python Basics 28
Binding and Accepting…
Accepting
 listen() finds connection attempts, but you must
use then accept them to form a connection
between your host and the remote client.
 You use the aptly-named accept() function in
order to do this.
import socket
server = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server.bind(“”,123)
server.listen(1)
connection, sock_addr = sock.accept()

Python Basics 29
Binding and Accepting…
 As you can see, the accept() function creates an
entirely new socket
 your original socket (in this case 'sock') can
continue listening for new connections
 while the newly created socket (in this case
'connection') can be used to send and receive data
from the client. Passive Participant
a-sock-1 l-sock a-sock-2

socket socket
Active 1 Active 2
Python Basics 30
Sending and Receiving
 Whether you have connected to a remote host or
accepted a connection from a client, sending and
receiving are what allow data to be transferred.
 The send() and recv() functions from the socket
module are basically identical - the only
difference is whether data is being sent or
received.
 They both take one argument
 send() takes the data to be sent as an argument,
 recv() takes the number of bytes to be received
as an argument. recv() returns the data received.

Python Basics 31
Sending and Receiving…
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM
sock.connect(("iamu.edu.et", 123
nickname = "NICK mamush”
encoded_nick = bytes(nickname, 'utf-8')
sock.send(encoded_nick)
sock.send(encoded_user)

Python Basics 32
Client/server socket interaction: TCP
server (running on hostid) client
create socket,
port=x, for incoming
request:
serverSocket = socket()

wait for incoming create socket,


connection request
TCP connect to hostid, port=x
connectionSocket = connection setup clientSocket = socket()
serverSocket.accept()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket

Python Basics 2-33


Example app: TCP client
Python TCPClient
from socket import *
serverName = ’servername’
create TCP socket for serverPort = 1200
server, remote port 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input(‘Input lowercase sentence:’)
No need to attach server clientSocket.send(sentence)
name, port
modifiedSentence = clientSocket.recv(1024)
print ‘From Server:’, modifiedSentence
clientSocket.close()

Python Basics 2-34


Example app: TCP server
Python TCPServer
from socket import *
create TCP welcoming
serverPort = 1200
socket serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind((‘’,serverPort))
server begins listening for
incoming TCP requests
serverSocket.listen(1)
print ‘The server is ready to receive’
loop forever while 1:
server waits on accept() connectionSocket, addr = serverSocket.accept()
for incoming requests, new
socket created on return
sentence = connectionSocket.recv(1024)
read bytes from socket (but
not address as in UDP) capitalizedSentence = sentence.upper()
close connection to this
connectionSocket.send(capitalizedSentence)
client (but not welcoming connectionSocket.close()
socket)
Python Basics 2-35
Python Internet Modules
 A list of some important modules in Python Network/Internet
programming.
Protocol Common function Port No Python module

HTTP Web pages 80 httplib, urllib, xmlrpclib

NNTP Usenet news 119 nntplib

FTP File transfers 20 ftplib, urllib

SMTP Sending email 25 smtplib

POP3 Fetching email 110 poplib

IMAP4 Fetching email 143 imaplib

Telnet Command lines 23 telnetlib

Gopher Document transfers 70 gopherlib, urllib Python Basics 2-36


Using smtplib
 s = smtplib.SMTP([host[, port]])
 Create SMTP object with given connection parameters
 r = s.sendmail(from, to, msg
[, mopts[, ropts]])
 from : sender address
 to : list of recipient addresses
 msg : RFC822-formatted message (including all necessary
headers)
 mopts, ropts : ESMTP option lists

Python Basics 2-37


SMTP Example
import smtplib
smtpObj = smtplib.SMTP(“localhost")
sender ='nebfikru@gmail.com'
receivers = ['nebiat.fikru@amu.edu.et']
message = """From:<nebfikru@gmail.com>
To: <nebiat.fikru@amu.edu.et>
Subject: SMTP e-mail test

This is a test e-mail message.


"""
smtpObj.sendmail(sender, receivers, message)

print("Successfully sent email")

Python Basics 2-38


Chapter 2: summary
our study of network apps now complete!
 application architectures  specific protocols:
 client-server  HTTP
 P2P  FTP
 application service
requirements:  SMTP, POP, IMAP
 reliability, bandwidth,  DNS
delay  P2P: BitTorrent, DHT
 Internet transport service  socket programming: TCP,
model UDP sockets
 connection-oriented,
reliable: TCP
 unreliable, datagrams:
UDP
Python Basics 2-39
Chapter 2: summary
most importantly: learned about protocols!
 typical request/reply important themes:
message exchange:
 client requests info or
 control vs. data msgs
service  in-band, out-of-band
 server responds with  centralized vs. decentralized
data, status code  stateless vs. stateful
 message formats:  reliable vs. unreliable msg
 headers: fields giving
info about data transfer
 data: info being  “complexity at network
communicated edge”

Python Basics 2-40


Chapter 1
Additional Slides

Python Basics 2-41


application
packet (www browser,

analyzer email client)


application

OS
packet Transport (TCP/UDP)

capture copy of all Network (IP)


Ethernet
frames Link (Ethernet)
(pcap) sent/receive
d Physical

Python Basics 2-42

You might also like