2017-03-27
Socket programming
Socket
programming
What is a socket?
goal: learn how to build client/server applications that communicate using
sockets
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
2-2
1
2017-03-27
What is a socket?
Socket is an interface between application and network
(the lower levels of the protocol stack)
The application creates a socket
The socket type dictates the style of communication
reliable vs. best effort
connection-oriented vs. connectionless
Once a socket is setup the application can
pass data to the socket for network transmission
receive data from the socket (transmitted through the
network, received from some other host)
Most popular types of sockets
• TCP socket UDP socket
• Type: SOCK_STREAM Type: SOCK_DGRAM
• reliable delivery unreliable delivery
• in-order guaranteed no order guarantees
• connection-oriented no notion of “connection” –
• bidirectional app indicates destination
for each packet
can send or receive
2
2017-03-27
Ports
• Each host machine has an IP
address (or more!) Port 0
Port 1
• Each host has 65,536 ports (2?)
Port 65535
• As you know some ports are
reserved for specific apps
• 20,21: FTP
• 23: Telnet A socket provides an interface to send
• 80: HTTP data to/from the network through a
• see RFC 1700 (about 2000 ports port
are reserved)
Addresses, Ports and Sockets
Like apartments and mailboxes
You are the application
Your apartment building address is the address
Your mailbox is the port
The post-office is the network
The socket is the key that gives you access to the right
mailbox (one difference: assume outgoing mail is placed by
you in your mailbox)
Q: How do you choose which port a socket connects to?
3
2017-03-27
Socket programming
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.
2-7
Ports
• Each host machine has an IP
address (or more!) Port 0
Port 1
• Each host has 65,536 ports (2?)
Port 65535
• As you know some ports are
reserved for specific apps
• 20,21: FTP
• 23: Telnet A socket provides an interface to send
• 80: HTTP data to/from the network through a
• see RFC 1700 (about 2000 ports port
are reserved)
4
2017-03-27
Addresses, Ports and Sockets
Like apartments and mailboxes
You are the application
Your apartment building address is the address
Your mailbox is the port
The post-office is the network
The socket is the key that gives you access to the right
mailbox (one difference: assume outgoing mail is placed by
you in your mailbox)
Q: How do you choose which port a socket connects to?
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
2-
10
5
2017-03-27
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
Application 2-11
Example app: UDP client
Python UDPClient
include Python’s socket
library from socket import *
serverName = ‘hostname’
serverPort = 12000
create UDP socket for clientSocket = socket(socket.AF_INET,
server
socket.SOCK_DGRAM)
get user keyboard
input message = raw_input(’Input lowercase sentence:’)
Attach server name, port to
message; send into socket clientSocket.sendto(message,(serverName, serverPort))
read reply characters from modifiedMessage, serverAddress =
socket into string
clientSocket.recvfrom(2048)
print out received string print modifiedMessage
and close socket
clientSocket.close()
2-
12
6
2017-03-27
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 serverSocket.bind(('', serverPort))
number 12000
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
2-
13
Socket programming with TCP
client must contact server when contacted by client, server
TCP creates new socket for server
server process must first be process to communicate with
running that particular client
allows server to talk with
server must have created multiple clients
socket (door) that welcomes
client’s contact source port numbers used to
distinguish clients
client contacts server by:
Creating TCP socket, specifying
IP address, port number of
server process application viewpoint:
when client creates socket: client TCP provides reliable, in-order
TCP establishes connection to byte-stream transfer (“pipe”)
server TCP
between client and server
2-
14
7
2017-03-27
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
2-
15
Example app: TCP client
Python TCPClient
from socket import *
serverName = ’servername’
create TCP socket for serverPort = 12000
server, remote port 12000 clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input(‘Input lowercase sentence:’)
clientSocket.send(sentence)
No need to attach server modifiedSentence = clientSocket.recv(1024)
name, port
print ‘From Server:’, modifiedSentence
clientSocket.close()
2-
16
8
2017-03-27
Example app: TCP server
Python TCPServer
from socket import *
create TCP welcoming serverPort = 12000
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()
for incoming requests, new
connectionSocket, addr = serverSocket.accept()
socket created on return
sentence = connectionSocket.recv(1024)
read bytes from socket (but
not address as in UDP)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
close connection to this connectionSocket.close()
client (but not welcoming
socket)
2-
17
The bind function
The bind function associates and (can exclusively) reserves a
port for use by the socket
int status = bind(sockid, &addrport, size);
status: error status, = -1 if bind failed
sockid: integer, socket descriptor
addrport: struct sockaddr, the (IP) address and port of the machine
(address usually set to INADDR_ANY – chooses a local address)
size: the size (in bytes) of the addrport structure
bind can be skipped for both types of sockets. When and
why?
18
9
2017-03-27
Skipping the bind
SOCK_DGRAM:
if only sending, no need to bind. The OS finds a port each
time the socket sends a pkt
if receiving, need to bind
SOCK_STREAM:
destination determined during conn. setup
don’t need to know port sending from (during connection
setup, receiving end is informed of port)
19
On the connecting end
• When connecting to another host (i.e., connecting
end is the client and the receiving end is the server),
the OS automatically assigns a free port for the
outgoing connection.
• During connection setup, receiving end is informed
of port)
• You can however bind to a specific port if need be.
20
10
2017-03-27
Connection Setup
A connection occurs between two ends
Server: waits for an active participant to request connection
Client: initiates connection request to passive side
Once connection is established, server and client ends
are “similar”
both can send & receive data
either can terminate the connection
21
Server and clients
TCP Server
socket()
bind()
TCP Client listen()
socket() accept()
connection establishment
connect()
data request read()
write()
data reply write()
read()
read()
close() end-of-file notification
close()
22
11
2017-03-27
Connection setup steps
Client end: Server end:
step 1: listen (for
incoming requests)
step 2: request &
establish connection step 3: accept (a request)
step 4: send/recv
step 4: send/recv
Server The accepted connection
a-sock-1 l-sock a-sock-2 is on a new socket
The old socket continues
socket socket to listen for other active
participants
Client1 Client2
23
12