Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 159

15CS52- Computer Networks

Text Book
James F Kurose and Keith W Ross,
Computer Networking, A Top Down
approach, Sixth Edition, Pearson, 2017

2: Application Layer 1
15CS52- Computer Networks
 Module 1- Application layer
 Module 2- Transport layer
 Module 3- Network layer
 Module 4- Mobile and Multimedia Networks
 Module 5- Multimedia networking
Applications

2: Application Layer 2
Some network apps
 e-mail  voice over IP
 web  real-time video
 instant messaging conferencing- skype
 remote login  Movies on demand-
 P2P file sharing Netflix
 facebook
 multi-user network
 twitter
games
 streaming stored video
clips

2: Application Layer 3
Chapter 2: Application layer
 2.1 Principles of  2.6 P2P applications
network applications
 2.2 Web and HTTP
 2.3 FTP
 2.4 Electronic Mail
 SMTP, POP3, IMAP
 2.5 DNS

2: Application Layer 4
Chapter 2: Application Layer
Our goals:  learn about protocols
 conceptual, by examining popular
implementation application-level
aspects of network protocols
application protocols  HTTP
 transport-layer  FTP
service models  SMTP / POP3 / IMAP
 client-server
 DNS
paradigm
 peer-to-peer
paradigm

2: Application Layer 5
Principles of Network Applications
Creating a network app
application
transport
network
data link

write programs that physical

 run on (different) end


systems
 communicate over network
 e.g., web server software
communicates with
browser software application
transport
No need to write software network
data link

for network-core devices


application
physical
transport
network
 Network-core devices do data link
physical

not run user applications


 applications on end systems
allows for rapid app
development, propagation
2: Application Layer 6
Network Application architectures
 Designed by the app developer and dictates
how the app is structured over the various
end systems.
 Client-server
 Peer-to-peer (P2P)
 Hybrid of client-server and P2P

2: Application Layer 7
Client-server architecture
server:
 always-on host
 Services requests
 permanent IP address
 Eg: web,ftp,
telnet,email
Data center
client/server  housing a large no of host
 Powerful virtual server
 Google, Bing, Amazon, e-
Bay, Gmail, Yahoo,
facebook, twitter

2: Application Layer 8
Data center
facility composed of networked computers and
storage.
servers, storage subsystems, networking
switches, routers and firewalls, as well as the
cabling and physical racks used to organize and
interconnect the IT equipment.
Google has 30 to 50 data center
Can have hundreds of thousands of servers,
which must be powered and maintained.

2: Application Layer 9
Client-server architecture
clients:
 communicate with server
 may be intermittently
connected
 may have dynamic IP
addresses
 do not communicate
directly with each other
client/server

2: Application Layer 10
P2P architecture
 no always-on server
 arbitrary end systems
directly communicate
peer-peer
 peers are intermittently
connected and change IP
addresses
 Peers not owned by the
service provider, controlled
by users.
 Peers reside at Homes,
universities, office.
Highly scalable but difficult to
manage
2: Application Layer 11
P2P architecture
 Traffic intensive applications
 File sharing- BitTorrent
 Internet Telephony (skype)
 IPTV- Kankan and PPStream

 Self scalability- each peer can


request data and send data
 Cost effective as no server
infrastructure.

2: Application Layer 12
P2P architecture
Three Major Challenges
ISP Friendly –asymmetrical BW
usage
Security
Incentives- users volunteering for
sharing their BW, storage, and
computational resources.

2: Application Layer 13
Hybrid of client-server and P2P
Skype
 voice-over-IP P2P application
 centralized server: finding address of remote
party:
 client-client connection: direct (not through
server)
Instant messaging
 chatting between two users is P2P
 centralized service: client presence
detection/location
• user registers its IP address with central
server when it comes online
• user contacts central server to find IP
addresses of buddies
2: Application Layer 14
Class-2
Processes Communicating

Transport services available to


Applications

2: Application Layer 15
Processes communicating
Process: program running within a host.
 within same host, two processes communicate
using inter-process communication (defined by
OS).
 processes in different hosts communicate by
exchanging messages.
 A sending process creates and sends messages
into the network;
 a receiving process receives these messages and
possibly responds by sending messages back

2: Application Layer 16
Processes communicating
A network application consists of pairs of processes that send
messages.
A browser -client process ,a Web server - server process.
P2P- the peer that is downloading the file is labeled as the
client, and the peer that is uploading the file is labeled as the
server.
Client process: process that initiates communication
Server process: process that waits to be contacted

 Note: applications with P2P architectures have


client processes & server processes

2: Application Layer 17
 In the context of a communication session
between a pair of processes, the process
that initiates the communication is labeled
as the client.
 The process that waits to be contacted to
begin the session is the server.

2: Application Layer 18
Interface Between process and
Computer networks-Sockets
host or host or
 process sends/receives server
server
messages to/from its
socket. controlled by
app developer
 socket analogous to door process process

 sending process sends socket socket

message out door TCP with TCP with


buffers, Internet buffers,
 sending process relies on variables variables
transport infrastructure
on other side of door which
controlled
brings message to socket by OS
at receiving process

2: Application Layer 19
Socket
 The interface between the application layer
and the transport layer within a host.
 referred to as the Application Programming
Interface (API) between the application and
the network.
The only control that the application developer
has on the transport-layer side is
 (1) choice of transport protocol; (2) ability to
fix a few parameters maximum buffer and
maximum segment sizes

2: Application Layer 20
Addressing processes
 to receive messages, process must have
identifier
 host device has unique 32-bit IP address
 Q: does IP address of host suffice for
identifying the process?

2: Application Layer 21
Addressing processes

 To identify the receiving process, two pieces of


information need to be specified:
 (1) the address of the host . (IP address)
 (2) an identifier that specifies the receiving
process in the destination host. (port number)

 host device has unique 32-bit IP address

2: Application Layer 22
Addressing processes
 identifier includes both IP address and port numbers
associated with process on host.
 Popular applications have been assigned specific port
numbers.
 Example port numbers:
 HTTP Web server: 80
 SMTP Mail server: 25
 to send HTTP message to gaia.cs.umass.edu web
server:
 IP address: 128.119.245.12
 Port number: 80
 well-known port numbers for all Internet standard
protocols
2: Application Layer 23
Transport services Available to
Applications
 sending side pushes messages through the socket.
 At the other side of the socket, the transport-
layer protocol has the responsibility of getting the
messages to the socket of the receiving process.
Broadly classify the possible services along four
dimensions:
 reliable data transfer
 Throughput
 timing
 security.

2: Application Layer 24
Reliable data transfer
If a protocol provides a guaranteed data delivery
service, it is said to provide reliable data
transfer.
 For many applications—such as electronic mail,
file transfer, remote host access, Web document
transfers, and financial applications can not
tolerate data loss
 loss-tolerant applications
 multimedia applications such as conversational
audio/video that can tolerate some amount of data loss.

2: Application Layer 25
Throughput
The rate at which the sending process can deliver bits
to the receiving process.
transport-layer protocol could provide, guaranteed
available throughput at some specified rate.
The application could request a guaranteed throughput
of r bits/sec, and the transport protocol would then
ensure that the available throughput is always at
least r bits/sec.
Example of internet telephone application ,
app encodes voice at 32kps then if transfer layer is
unable to provide that speed then app need to
encode at slower rate but not less than half of
required.

2: Application Layer 26
bandwidth-sensitive applications
Applications that have throughput
requirements.
Eg :Many current multimedia applications
Elastic applications
can make use of as much, or as little,
throughput as happens to be available.
Electronic mail, file transfer, and Web
transfers are all elastic applications.

2: Application Layer 27
Transport services Available to
Applications
Timing
 A transport-layer protocol can also provide timing guarantees
 Interactive real-time applications, such as Internet telephony,
virtual environments, teleconferencing, and multiplayer games
require low delay to be “effective”.
 For non-real-time applications, lower delay is always preferable
to higher delay, but no tight constraint is placed on the end-
to-end delays.

Security
 A transport protocol can provide an application
with one or more security services.
 Encryption, data integrity, …
2: Application Layer 28
Class 3
Transport services provided by
the Internet
Application layer protocols

2: Application Layer 29
Transport services provided by the Internet

first decisions you have to make is whether to use UDP or TCP.

Requirements of selected network applications


Application Data loss Throughput Time Sensitive

file transfer no loss elastic no


e-mail no loss elastic no
Web documents no loss elastic no
real-time audio/video loss-tolerant audio: 5kbps-1Mbps yes, 100’s msec
video:10kbps-5Mbps
stored audio/video loss-tolerant same as above yes, few secs
interactive games loss-tolerant few kbps -10kbps yes, 100’s msec
instant messaging no loss elastic yes and no

2: Application Layer 30
TCP services
 connection-oriented service
 a reliable data transfer service.
connection-oriented: setup required between
client and server processes.

 After the Three way handshaking phase,


 A TCP connection is said to exist between the
sockets of the two processes. full-duplex
connection.
 Tear down
2: Application Layer 31
Reliable data transfer service
without error and in the proper order
with no missing or duplicate bytes.
flow control: sender won’t overwhelm
receiver
congestion control: throttle sender when
network overloaded

2: Application Layer 32
Internet transport protocols services

UDP service:

 lightweight transport protocol, providing minimal


services.
 connectionless, no handshaking.
 unreliable data transfer service—no guarantee.
 messages that do arrive at the receiving process
may arrive out of order.
 No congestion-control mechanism, so the sending
side of UDP can pump data into the layer below
(the network layer) at any rate it pleases.

2: Application Layer 33
Services Not Provided by
Internet Transport Protocols
 Transport protocol services along four dimensions:
reliable data transfer, throughput, timing, and
security.
 Which of these services are provided by TCP and UDP?
 TCP- reliable, Security
 TCP can be easily enhanced at the application layer with
SSLto provide security services
 Today’s Internet can often provide satisfactory service
to time-sensitive applications, but it cannot provide any
timing or throughput guarantees.

2: Application Layer 34
Popular Internet applications, their application-
layer protocols, and their underlying transport
protocols
Application Underlying
Application layer protocol transport protocol

e-mail SMTP [RFC 2821] TCP


remote terminal access Telnet [RFC 854] TCP
Web HTTP [RFC 2616] TCP
file transfer FTP [RFC 959] TCP
streaming multimedia HTTP (eg Youtube), TCP or UDP
RTP [RFC 1889]
Internet telephony SIP, RTP, proprietary
(e.g., Skype) typically UDP

2: Application Layer 35
Secure TCP
 Neither TCP nor UDP provide any encryption
 An enhancement for TCP, called Secure
Sockets Layer (SSL)
 TCP-enhanced-with-SSL
 provides critical process-to-process security
services, including encryption, data integrity,
and end-point authentication.
 Enhancements being implemented in the
application layer

2: Application Layer 36
Application layer protocols
 network processes communicate with each
other by sending messages into sockets.
 But how are these messages structured?
 What are the meanings of the various
fields in the messages?
 When do the processes send the
messages?

2: Application Layer 37
An application-layer protocol defines:
The types of messages exchanged, for
example, request messages and response
messages.
The syntax of the various message types,
such as the fields in the message and how the
fields are delineated.
The semantics of the fields, that is, the
meaning of the information in the fields.
Rules for determining when and how a
process sends messages and responds to
messages.
2: Application Layer 38
 Web’s application-layer protocol, HTTP is
available as an RFC 1845 and RFC2610 .-
public domain
 If a browser developer follows the rules
of the HTTP RFC, the browser will be able
to retrieve Web pages from any Web
server that has also followed the rules of
the HTTP RFC.
 Skype uses proprietary application-layer
protocols

2: Application Layer 39
2.2Web and HTTP
 Web page consists of objects.
 Object can be HTML file, JPEG image, Java
applet, audio file,…
 Web page consists of base HTML-file which
includes several referenced objects
 Each object is addressable by a URL
 Example URL:

www.someschool.edu/someDept/pic.gif

host name path name

2: Application Layer 40
HTTP overview

HTTP: hypertext
transfer protocol HT
TP
r
equ
 Web’s application layer PC running HT est
TP
protocol Explorer res
pon
se
 client/server model
 client: browser that
e st
u
requests, receives, P r eq se Server
T o n
“displays” Web objects HT r es
p running
T P Apache Web
 server: Web server HT
server
sends objects in
response to requests
Mac running
Navigator

2: Application Layer 41
HTTP overview (continued)
Uses TCP: HTTP is “stateless”
 client initiates TCP  server maintains no
connection (creates socket) information about
to server, port 80 past client requests
 server accepts TCP
connection from client aside
Protocols that maintain
 HTTP messages (application- “state” are complex!
layer protocol messages)  past history (state) must
exchanged between browser be maintained
(HTTP client) and Web  if server/client crashes,
server (HTTP server)
their views of “state” may
 TCP connection closed
be inconsistent, must be
reconciled

2: Application Layer 42
HTTP connections
Nonpersistent HTTP Persistent HTTP
 At most one object is  Multiple objects can
sent over a TCP be sent over single
connection. TCP connection
 each request/response between client and
pair be sent over a server.
separateTCPconnectio all of the requests and
n their corresponding
responses be sent over
the same
TCPconnection

2: Application Layer 43
Nonpersistent HTTP
(contains text,
Suppose user enters URL www.someSchool.edu/someDepartment/home.index
references to 10
jpeg images)

1a. HTTP client initiates TCP


connection to HTTP server
(process) at
1b. HTTP server at host
www.someSchool.edu waiting
www.someSchool.edu on port 80
for TCP connection at port 80.
“accepts” connection,
notifying client
2. HTTP client sends HTTP
request message (containing
URL) into TCP connection 3. HTTP server receives request
socket. Message indicates message, forms response
that client wants object message containing requested
someDepartment/home.index object, and sends message
into its socket

time
2: Application Layer 44
Nonpersistent HTTP (cont.)

4. HTTP server closes TCP


connection.
5. HTTP client receives response
message containing html file,
displays html. Parsing html
file, finds 10 referenced jpeg
objects
time 6. Steps 1-5 repeated for each
of 10 jpeg objects

2: Application Layer 45
Non-Persistent HTTP: Response time
Definition of RTT: time for a
small packet to travel from
client to server and back.
Response time: initiate TCP
connection
 one RTT to initiate TCP
RTT
connection
request
 one RTT for HTTP request file
time to
and first few bytes of RTT
transmit
HTTP response to return file
file
 file transmission time received
total = 2RTT+transmit time
time time

2: Application Layer 46
Persistent HTTP

Nonpersistent HTTP issues: Persistent HTTP


 requires 2 RTTs per object  server leaves connection
 OS overhead for each TCP open after sending
connection response
 browsers often open parallel  subsequent HTTP messages
TCP connections to fetch between same
referenced objects client/server sent over
open connection
 client sends requests as
soon as it encounters a
referenced object
 as little as one RTT for all
the referenced objects

2: Application Layer 47
HTTP request message
 two types of HTTP messages: request, response
 HTTP request message:
 ASCII (human-readable format)

request line
(GET, POST, GET /somedir/page.html HTTP/1.1
HEAD commands) Host: www.someschool.edu
User-agent: Mozilla/4.0
header Connection: close
lines Accept-language:fr

Carriage return,
line feed (extra carriage return, line feed)
indicates end
of message
 The GET method is used when the browser
requests an object, with the requested object
identified in the URL field.
 The browser is requesting the object
/somedir/page.html.
 The browser implements version HTTP/1.1.
 The header line Host: www.someschool.edu
specifies the host on which the object resides.
 the Connection: close header line, the browser
is telling the server that it doesn’t want to
bother with persistent connections;
 it wants the server to close the connection
after sending the requested object.
2: Application Layer 49
 The User-agent: header line specifies the
user agent, that is, the browser type.
 The user agent is Mozilla/5.0, a Firefox
browser.
 Acceptlanguage: header indicates that the
user prefers to receive a French version of
the object, if such an object exists on the
server;

2: Application Layer 50
HTTP request message: general format

2: Application Layer 51
 GET - Requests data from a specified
resource
 POST - Submits data to be processed to a
specified resource

2: Application Layer 52
 The entity body is empty with the GET
method, but is used with the POST
method.
 An HTTP client often uses the POST
method when the user fills out a form—for
example, when a user provides search
words to a search engine.
 If the value of the method field is POST,
then the entity body contains what the
user entered into the form fields.

2: Application Layer 53
 For example, if a form uses the GET method,
has two fields, and the inputs to the two fields
are monkeys and bananas, then the URL will
have the structure
www.somesite.com/animalsearch?
monkeys&bananas.
 The HEAD method is similar to the GET
method.
 When a server receives a request with the
HEAD method, it responds with an HTTP
message
2: Application Layer 54
 Application developers often use the HEAD
method for debugging.
 The PUT method is often used in
conjunction with Web publishing tools.
 PUT allows a user to upload an object to a
specific path (directory) on a specific Web
server.
 The DELETE method allows a user, or an
application, to delete an object on a Web
server
2: Application Layer 55
Uploading form input
Post method:
 Web page often
includes form input URL method:
 Input is uploaded to  Uses GET method
server in entity body  Input is uploaded in
URL field of request
line:

www.somesite.com/animalsearch?monkeys&banana

2: Application Layer 56
Method types
HTTP/1.0 HTTP/1.1
 GET  GET, POST, HEAD
 POST  PUT
 HEAD  uploads file in entity
body to path specified
 asks server to leave
in URL field
requested object out of
response  DELETE
 deletes file specified in
the URL field

2: Application Layer 57
HTTP response message
status line
(protocol
status code HTTP/1.1 200 OK
status phrase) Connection close
Date: Thu, 06 Aug 1998 12:00:15 GMT
header Server: Apache/1.3.0 (Unix)
lines Last-Modified: Mon, 22 Jun 1998 …...
Content-Length: 6821
Content-Type: text/html

data, e.g., data data data data data ...


requested
HTML file
Three sections:
An initial status line
six header lines
The entity body.
The entity body -it contains the requested object
itself.
The status line has three fields: the protocol
version field, a status code, and a corresponding
status message.
The status line indicates that the server is using
HTTP/1.1 and that everything is OK

2: Application Layer 59
 The server uses the Connection: close header line to
tell the client that it is going to close the
TCPconnection after sending the message.
 The Date: header line indicates the time and date
when the HTTP response was created and sent by
the server.
 The Server:header line indicates that the message
was generated by an Apache Web server.
 It is analogous to the User-agent:
 The Last-Modified: header line indicates the time
and date when the object was created or last
modified.

2: Application Layer 60
 The Content-Length: header line indicates
the number of bytes in the object being
sent.
 The Content-Type: header line indicates
that the object in the entity body is
HTMLtext.

2: Application Layer 61
HTTP response status codes
The status code and associated phrase indicate the
result of the request.
In first line in server->client response message.
A few sample codes:
200 OK
 request succeeded, requested object later in this message
301 Moved Permanently
 requested object moved, new location specified later in
this message (Location:)
400 Bad Request
 request message not understood by server
404 Not Found
 requested document not found on this server
505 HTTP Version Not Supported 2: Application Layer 62
2: Application Layer 63
User-server state: cookies
 It is often desirable for a Web site to
identify users, either because the server
wishes to restrict user access or because it
wants to serve content as a function of the
user identity. For these purposes, HTTP uses
cookies.
 Cookies, defined in [RFC 6265], allow sites to
keep track of users

2: Application Layer 64
User-server state: cookies
Example:
Many major Web sites
 Susan always access
use cookies
Internet always from PC
Four components:
 visits specific e-
1) cookie header line of
HTTP response message commerce site for first
2) cookie header line in time
HTTP request message  when initial HTTP
3) cookie file kept on
user’s host, managed by requests arrives at site,
user’s browser site creates:
4) back-end database at  unique ID
Web site
 entry in backend
database for ID

2: Application Layer 65
Cookies: keeping “state” (cont.)
client server
ebay 8734
usual http request msg
Amazon server
cookie file usual http response creates ID
Set-cookie: 1678 1678 for user create
ebay 8734 entry
amazon 1678
usual http request msg
cookie: 1678 cookie- access
specific
one week later: usual http response msg action backend
database
access
ebay 8734 usual http request msg
amazon 1678 cookie: 1678 cookie-
spectific
usual http response msg action

2: Application Layer 66
Cookies (continued)
aside
What cookies can bring: Cookies and privacy:
 authorization  cookies permit sites to
 shopping carts learn a lot about you
 you may supply name
 recommendations
and e-mail to sites
 user session state
(Web e-mail)
How to keep “state”:
 protocol endpoints: maintain state
at sender/receiver over multiple
transactions
 cookies: http messages carry state

2: Application Layer 67
Web caching
 a proxy server—is a network entity that
satisfies HTTP requests on the behalf of an
origin Web server.
 own disk storage and keeps copies of
recently requested objects in this storage.
 A user’s browser can be configured so that
all of the user’s HTTPrequests are first
directed to the Web cache.

2: Application Layer 68
Web caches (proxy server)
Goal: satisfy client request without involving origin server

 user sets browser: Web origin


server
accesses via cache
 browser sends all HTTP Proxy
HT
requests to cache TP
req server q uest
H u P re
T
client TP e st T T o n se
 object in cache: cache res H
r es
p
pon P
returns object se H TT
e st
 else cache requests r eq
u
object from origin server, T P o nse
HT p
r es
then returns object to T TP
client H

client
origin
server
More about Web caching
 cache acts as both Why Web caching?
client and server  reduce response time
 typically cache is for client request
installed by ISP  reduce traffic on an
(university, company, institution’s access
residential ISP) link.
 Reduce web traffic in
the Internet as a
whole, thereby
improving the
performance of all
applications.
2: Application Layer 70
Caching example
origin
Assumptions servers
 average object size = 1000000
public
bits= 1Mb=1 Mega bits Internet
 avg. request rate from
institution’s browsers to origin
servers = 15/sec
 delay from router on the 15 Mbps
access link
Internet side of access link to
any origin server and back to institutional
network
router = 2 sec 100 Mbps LAN

Consequences
 total delay = Internet delay +
access delay + LAN delay institutional
= 2 sec + 1 sec+ milliseconds cache
Caching example (cont)
origin
possible solution servers
 increase bandwidth of access
public
link to, say, 100 Mbps Internet
consequence
 Total delay = Internet delay +
access delay + LAN delay 100 Mbps
= 2 sec + msecs + msecs access link
 often a costly upgrade
institutional
network
100 Mbps LAN

institutional
cache

2: Application Layer 72
Caching example (cont)
possible solution: install origin
cache servers
 suppose hit rate is 0.4
public
consequence Internet
 40% requests will be
satisfied almost immediately
( 10ms)
 60% requests satisfied by 15 Mbps
origin server access link
 utilization of access link
institutional
reduced to 60%, resulting in network
negligible delays (say 1.0 to 100 Mbps LAN
0.6 sec)
 total avg delay =0.4*(0.01)
secs + .6*(2.0)s = 1.2 secs
institutional
cache
Content Distribution Networks(CDNs)
A CDN Company installs many geographically
distributed caches throughout the Internet.
Shared CDN- Akamai, Limelight
Dedicated CDN- google and Microsoft

2: Application Layer 74
Conditional GET
 object housed in the Web server may have
been modified since the copy was cached at
the client.
 A mechanism that allows a cache to verify
that its objects are up to date- conditional
GET.
 (1) the request message uses the GET
method
 (2) the request message includes an If-
ModifiedSince: header line.
2: Application Layer 75
 On the behalf of a requesting browser, a proxy
cache sends a request message to a Web server:
GET /fruit/kiwi.gif HTTP/1.1
Host: www.exotiquecuisine.com
 the Web server sends a response message with
the requested object to the cache:
HTTP/1.1 200 OK
Date: Sat, 8 Oct 2011 15:39:29
Server: Apache/1.3.0 (Unix)
Last-Modified: Wed, 7 Sep 2011 09:23:24 Content-
Type: image/gif
(data data data data data ...)

2: Application Layer 76
 one week later, another browser requests the same
object via the cache, and the object is still in the
cache.
 The cache performs an up-to-date check by issuing
a conditional GET.
 Specifically, the cache sends:
GET /fruit/kiwi.gif HTTP/1.1
Host: www.exotiquecuisine.com
If-modified-since: Wed, 7 Sep 2011 09:23:24
 This conditional GET is telling the server to send
the object only if the object has been modified
since the specified date.

2: Application Layer 77
 The Web server sends a response
message to the cache:
HTTP/1.1 304 Not Modified
Date: Sat, 15 Oct 2011 15:39:29
Server: Apache/1.3.0 (Unix)
(empty entity body)

2: Application Layer 78
Conditional GET

 Goal: don’t send object if cache server


cache has up-to-date cached HTTP request msg
version If-modified-since:
object
 cache: specify date of <date>
not
cached copy in HTTP request modified
HTTP response
If-modified-since: HTTP/1.0
<date> 304 Not Modified
 server: response contains no
object if cached copy is up-
HTTP request msg
to-date: If-modified-since:
HTTP/1.0 304 Not <date> object
Modified modified
HTTP response
HTTP/1.0 200 OK
<data>
2: Application Layer 79
Chapter 2: Application layer
 2.1 Principles of  2.6 P2P applications
network applications
 2.2 Web and HTTP
 2.3 FTP
 2.4 Electronic Mail
 SMTP, POP3, IMAP
 2.5 DNS

2: Application Layer 80
FTP: the file transfer protocol

FTP file transfer


FTP FTP
user client server
interface
user
at host remote file
local file system
system

 transfer file to/from remote host


 client/server model
 client: side that initiates transfer (either to/from
remote)
 server: remote host
 ftp: RFC 959
 ftp server: port 21

2: Application Layer 81
FTP HTTP
Run on top of TCP Run on top of TCP
Two parallel TCP Sends request and
connection to response into Same
transfer file- control TCP connection.
connection, data Send its control
connection information in-band
Send its control
information out of
band
2: Application Layer 82
FTP: separate control, data connections
TCP control connection
 FTP client contacts FTP server port 21
at port 21, TCP is transport
protocol TCP data connection
 client authorized over control FTP port 20 FTP
connection client server
 client browses remote  server opens another TCP
directory by sending commands
data connection to transfer
over control connection.
another file.
 when server receives file  control connection: “out of
transfer command, server
band”
opens 2nd TCP connection (for
 FTP server maintains “state”:
file) to client
current directory, earlier
 after transferring one file,
authentication
server closes data connection.
2: Application Layer 83
FTP commands, responses

Sample commands: Sample return codes


 sent as ASCII text over  status code and phrase (as
control channel(7 bit) in HTTP)
 USER username  331 Username OK,
 PASS password password required
 LIST return list of file in  125 data connection
current directory already open;
transfer starting
 RETR filename retrieves
 425 Can’t open data
(gets) file connection
 STOR filename stores  452 Error writing
(puts) file onto remote file
host

2: Application Layer 84
Electronic Mail outgoing
message queue
user mailbox
user
Three major components: agent
 user agents mail
user
 mail servers server
agent
 simple mail transfer protocol:
SMTP mail
SMTP
server user

User Agent SMTP agent

 “mail reader”
SMTP
 composing, editing, reading mail user
agent
mail messages server
 e.g. Outlook, Mozilla
user
Thunderbird
agent
 outgoing, incoming messages user
stored on server agent

2: Application Layer 85
Electronic Mail: mail servers
user
Mail Servers agent
 mailbox contains incoming
mail
user
messages for user server
agent
 message queue of outgoing
SMTP
(to be sent) mail messages mail
server user
 SMTP protocol between mail
servers to send email
SMTP agent

messages SMTP
 client: sending mail mail user
agent
server server
 “server”: receiving mail
user
server agent
user
agent

2: Application Layer 86
Electronic Mail: SMTP
 uses TCP to reliably transfer email message from client
to server, port 25
 direct transfer: sending server to receiving server
 three phases of transfer
 handshaking (greeting)
 transfer of messages
 closure
 command/response interaction
 commands: ASCII text
 response: status code and phrase

 messages must be in 7-bit ASCII

2: Application Layer 87
SMTP
 Transfers messages from senders’ mail servers
to the recipients’ mail servers.
 much older than HTTP.
 Restricts the body of all mail messages to simple
7-bit ASCII
 7-bit ASCII restriction is a bit of a pain—it
requires binary multimedia data to be encoded to
ASCII before being sent over SMTP;
 it requires the corresponding ASCII message to
be decoded back to binary after SMTP
transport.

2: Application Layer 88
Scenario: Alice sends message to Bob
1) Alice uses UA to compose 4) SMTP client sends Alice’s
message and “to” message over the TCP
bob@someschool.edu connection
2) Alice’s UA sends message 5) Bob’s mail server places the
to her mail server; message message in Bob’s mailbox
placed in message queue 6) Bob invokes his user agent
3) Client side of SMTP opens to read message
TCP connection with Bob’s
mail server

1 mail
mail
server user
user server
2 agent
agent 3 6
4 5

2: Application Layer 89
 Does not use intermediate mail servers for
sending mail.
 The TCP connection is a direct connection.
 The message does not get placed in some
intermediate mail server.

2: Application Layer 90
how SMTP transfers a message from a
sending mail server to a receiving mail server.

 The client SMTP has TCP establish a


connection to port 25 at the server SMTP.
 client perform some application-layer
handshaking—SMTP clients and servers
introduce themselves
 SMTP client indicates the e-mail address of
the sender and the e-mail address of the
recipient.
 The client sends messages.
 Same connection for other messages.

2: Application Layer 91
Sample SMTP interaction
S: 220 hamburger.edu
C: HELO crepes.fr
S: 250 Hello crepes.fr, pleased to meet you
C: MAIL FROM: <alice@crepes.fr>
S: 250 alice@crepes.fr... Sender ok
C: RCPT TO: <bob@hamburger.edu>
S: 250 bob@hamburger.edu ... Recipient ok
C: DATA
S: 354 Enter mail, end with "." on a line by itself
C: Do you like ketchup?
C: How about pickles?
C: .
S: 250 Message accepted for delivery
C: QUIT
S: 221 hamburger.edu closing connection

2: Application Layer 92
SMTP: final words
 SMTP uses persistent connections
 SMTP requires message (header & body) to be in
7-bit ASCII
 SMTP server uses CRLF.CRLF to determine end
of message

2: Application Layer 93
Comparison with HTTP
HTTP SMTP
Transfers files from a web Transfers files from one mail
server to a web client server to another mail server.
Persistent Persistent
Pull protocol Push protocol
 Someone loads  The Sending mail server

information on a web pushes the file to the


server and users use receiving mail server.
HTTP to pull info.
Does not impose any Msg+body- to be in 7 bit
restriction on msg format ASCII format
each object encapsulated in All of the msg’s objects into
its own response msg one msg

94
Mail message format

SMTP: protocol for


exchanging email msgs header
blank
RFC 5322: standard for text
line
message format:
 header lines, e.g.,
 To: body
 From:
 Subject:

different from SMTP


commands!
 body
 the “message”, ASCII
characters only

2: Application Layer 95
Mail access protocols
SMTP SMTP access user
user
agent protocol agent

sender’s mail receiver’s mail


server server
 SMTP: delivery/storage to receiver’s server
 User runs a user agent on the local PC but accesses its mailbox
stored on an always-on shared mail server.
 Mail access protocol: retrieval from server
 POP3: Post Office Protocol3
 IMAP: Internet Mail Access Protocol
 HTTP: gmail, Hotmail, Yahoo! Mail, etc.

2: Application Layer 96
POP3
 POP3 begins when the user agent opens a
TCP connection to the mail server on port
110.
 Three phases:
 Authorization –UA sends usr, pwd
 Transaction- UA retrieves msg, delete
 Update- occurs after the client has issued the
quit command

2: Application Layer 97
POP3 protocol C:telnet mailServer 110
S: +OK POP3 server ready
C: user bob
authorization phase S: +OK
C: pass hungry
 client commands:
S: +OK user successfully logged on
 user: declare username
C: list
 pass: password
S: 1 498
 server responses S: 2 912
 +OK S: .
 -ERR C: retr 1
S: <message 1 contents>
transaction phase, client: S: .
 list: list message numbers C: dele 1
 retr: retrieve message by C: retr 2
S: <message 1 contents>
number
S: .
 dele: delete
C: dele 2
 quit C: quit
S: +OK POP3 server signing off
2: Application Layer 98
 A user agent using POP3 can often be configured
to “download and delete” or to “download and
keep.”
 In the download-and-delete mode, the user agent
will issue the list, retr, and dele commands.
 list the size of each of the stored messages.
 The user agent then retrieves and deletes each
message from the server.
 After processing the quit command, the POP3
server enters the update phase and removes
messages 1 and 2 from the mailbox.

2: Application Layer 99
POP3
More about POP3
 Previous example uses “download and delete” mode.
 Bob cannot re-read e-mail if he changes client
 “Download-and-keep”: copies of messages on local
machine
 POP3 is stateless across sessions
 Does not provide any means for a user to create
remote folders and assign msgs to folder

2: Application Layer 100


IMAP(Internet mail Access
protocol)
 An IMAP server will associate each msg
with a folder- receipts’s INBOX folder.
 Keep all messages in one place: the
server
 Allows user to organize messages in
folders
 IMAP keeps user state across sessions:
 names of folders and mappings between
message IDs and folder name
 It has commands that permit a UA to
obtain components of msgs.
 Obtain Just msg header or just one
part of a multipart MIME msg
2: Application Layer 101
Web based E-mail
 Hot mail introduced web based access in
the mid 1990s.
 Google, Yahoo, major universities and
corporation.
 The user communicates with its remote
mailbox via HTTP.
 HTTP – between UA and sender’s mail
server or receiver’s mail server.
 SMTP- between two mail servers.

2: Application Layer 102


DNS: Domain Name System –The Internet’s
directory services
People: many identifiers:
 SSN, name, passport #. Prefer mnemonic
Internet hosts, routers:
 IP address (32 bit) - used for addressing datagrams
 Host name, e.g., www.yahoo.com - used by humans.
 A hostname such as www.eurecom.fr, which ends with the
country code.
 An IP address consists of four bytes and has a rigid
hierarchical structure.
 we need a directory service that translates
hostnames to IP addresses.

2: Application Layer 103


Domain Name System:
 distributed database implemented in hierarchy of many name
servers
 application-layer protocol that allows hosts to query the
distributed database(address/name translation)
 The DNS servers are often UNIX machines running the
Berkeley Internet Name Domain (BIND) software.

 The DNS protocol runs over UDP and uses port 53.

2: Application Layer 104


Example
 1. The user machine runs the client side of the DNS
application.
 2. The browser extracts the hostname,
www.someschool.edu, from the URL and passes the
hostname to the client side of the DNS application.
 3. The DNS client sends a query containing the
hostname to a DNS server.
 4. The DNS client eventually receives a reply, which
includes the IPaddress for the hostname.
 5. Once the browser receives the IPaddress from
DNS, it can initiate a TCPconnection to the HTTPserver
process located at port 80 at that IPaddress.

2: Application Layer 105


DNS Services
 hostname to IP address translation
 host aliasing
 A host with a complicated hostname can have one
or more alias names.
 For ex, a hostname such as relay1.west-
coast.enterprise.com could have, say, alias such as
enterprise.com.
 In this case, the hostname
relay1.westcoast.enterprise.com is said to be a
canonical hostname.
 obtain the canonical hostname for a supplied alias
hostname as well as the IPaddress of the host.

2: Application Layer 106


 mail server aliasing - e-mail addresses be mnemonic
 the hostname of the Hotmail mail server is more
complicated
 load distribution
 replicated Web servers: set of IP addresses for one
canonical name.
 Busy sites, such as cnn.com, are replicated over multiple
servers- different IP addresses.
 DNS rotation distributes the traffic among the
replicated servers.
 Content distribution companies such as Akamai have used
DNS in more sophisticated ways to provide Web content
distribution

2: Application Layer 107


Overview of how DNS works
Centralized design
one DNS server that contains all the mappings.
Clients simply direct all queries to the single DNS
server, and the DNS server responds directly to
the querying clients.
Why not centralize DNS?
single point of failure
traffic volume
distant centralized database
maintenance
doesn’t scale!

2: Application Layer 108


DNS-Distributed, Hierarchical
Database
 The DNS uses a large number of servers,
organized in a hierarchical fashion and
distributed around the world.
 No single DNS server has all of the mappings.
 The mappings are distributed across the DNS
servers.
 Three classes of DNS servers—
 root DNS servers
 top-level domain (TLD) DNS servers,
 authoritative DNS servers

2: Application Layer 109


Distributed, Hierarchical Database
Root DNS Servers

com DNS servers org DNS servers edu DNS servers

pbs.org poly.edu umass.edu


yahoo.com amazon.com
DNS servers DNS serversDNS servers
DNS servers DNS servers

Client wants IP for www.amazon.com; 1st approx:


 client queries a root server to find com DNS server
 client queries com DNS server to get amazon.com
DNS server
 client queries amazon.com DNS server to get IP
address for www.amazon.com
Root DNS servers
 13 root DNS servers (labeled A through M).
 Each of the 13 root DNS servers as if it were a single server, each
“server” is actually a network of replicated servers, for both
security and reliability purposes.
 All together, there are 247 root servers as of fall 2011.

a Verisign, Dulles, VA
c Cogent, Herndon, VA (also LA)
d U Maryland College Park, MD k RIPE London (also 16 other locations)
g US DoD Vienna, VA
h ARL Aberdeen, MD i Autonomica, Stockholm (plus
j Verisign, ( 21 locations) 28 other locations)
e NASA Mt View, CA m WIDE Tokyo (also Seoul,
f Internet Software C. Palo Alto, Paris, SF)
CA (and 36 other locations)

13 root name
servers worldwide
b USC-ISI Marina del Rey, CA
l ICANN Los Angeles, CA

2: Application Layer 111


TLD and Authoritative Servers
 Top-level domain (TLD) servers:
 responsible for com, org, net, edu, etc, and all
top-level country domains uk, fr, ca, jp.
 Verisign Global Registry Services maintains
servers for TLD servers for com
 Educause for edu TLD
 Authoritative DNS servers:
 An organization’s authoritative DNS server houses
DNS records.
 can be maintained by organization or service
provider

2: Application Layer 112


Local DNS Server
 does not strictly belong to hierarchy
 each ISP (residential ISP, company,
university) has one.
 also called “default name server”
 when host makes DNS query, query is sent
to its local DNS server
 acts as proxy, forwards query into hierarchy

2: Application Layer 113


DNS name root DNS server

resolution example
2
 Host at cis.poly.edu 3
TLD DNS server
wants IP address for 4
gaia.cs.umass.edu 5

iterated query: local DNS server


dns.poly.edu
 contacted server
7 6
replies with name of 1 8
server to contact
 “I don’t know this authoritative DNS server
dns.cs.umass.edu
name, but ask this requesting host
server” cis.poly.edu

gaia.cs.umass.edu

2: Application Layer 114


DNS name
resolution example root DNS server

recursive query: 2 3
 puts burden of name
7 6
resolution on
TLD DNS server
contacted name
server
 heavy load? local DNS server
dns.poly.edu 5 4

1 8

authoritative DNS server


dns.cs.umass.edu
requesting host
cis.poly.edu

gaia.cs.umass.edu

2: Application Layer 115


DNS caching
 when a DNS server receives a DNS reply it can
cache the mapping in its local memory.
 cache entries timeout (disappear) after
some time
 TLD servers typically cached in local name
servers
• Thus root name servers not often visited

2: Application Layer 116


DNS records and Messages
DNS: distributed db storing resource records (RR)
Each reply carries one or more RR

RR format: (name, value, type, ttl)

 Type=A
 Type=CNAME
 name is hostname
 name is alias name for some
 value is IP address
“canonical” (the real) name
 (Relay1.bar.foo.com,145.
www.ibm.com is really
37.93.126, A)
 Type=NS servereast.backup2.ibm.com
 name is domain (e.g. foo.com)
 value is canonical name

 value is hostname of
 Type=MX
authoritative name server for  value is canonical name of a
this domain
mailserver
 (Foo.com, dns.foo.com, NS)
 (foo.com,
mail.bar.foo.com,MX)
2: Application Layer
117
DNS Messages
query and reply messages, both with same message
format

2: Application Layer 118


DNS protocol, messages
DNS protocol : query and reply messages, both with same message format

msg header
 identification: 16 bit #
for query, reply to query
uses same #
 flags:
 query or reply
 recursion desired
 recursion available
 reply is authoritative

2: Application Layer 119


DNS protocol, messages

Name, type fields


for a query

RRs in response
to query

records for
authoritative servers

additional “helpful”
info that may be used

2: Application Layer 120


Inserting records into DNS
 example: new startup “Network Uptopia”
 register name networkuptopia.com at DNS registrar
(e.g., Network Solutions) –http://www.internic.net
 provide names, IP addresses of authoritative DNS server
(primary and secondary)
 registrar inserts two RRs into com TLD com server:

(networkuptopia.com, dns1.networkuptopia.com, NS)


(dns1.networkuptopia.com, 212.212.212.1, A)

Make sure Type A record for


www.networkuptopia.com; Type MX record for
mail.networkuptopia.com – enter into authoritative
server.
 How do people get IP address of your Web site?

2: Application Layer 121


Peer to peer Applications
 no always-on server
 arbitrary end systems
directly communicate peer-peer
 peers are intermittently
connected and change IP
addresses

 topics:
 File distribution –BitTorrent
 Database distributed over a
large community of peers-
Distributed Hash Table

2: Application Layer 122


P2P file distribution
 Distributing a large file from a single
server to a large number of hosts (called
peers).
 client-server file distribution
 the server must send a copy of the file to
each of the peers
 P2Pfile distribution,
 each peer can redistribute any portion of the
file it has received to any other peers, thereby
assisting the server in the distribution
process.
2: Application Layer 123
File Distribution: Server-Client vs P2P
Question : How much time to distribute file
from one server to N peers?
us: server upload
Server
rate
ui: peer i upload rate
u1 d1 u2
us d2
di: peer i download
File, size F rate
dN
Internet
uN
File distribution time: server-client
 server sequentially Server
sends N copies:
F u1 d1 u2
 NF/us time us d2

D min = min{d1,d2..,dn}. dN Network (with


abundant bandwidth)
F/dmin time to uN
download

Time to distribute F
= dcs = max { NF/us, F/dmin }
to N clients using
client/server approach
increases linearly in N
(for large N)
File distribution time: P2P
Server
 server must send one
F u1 d1 u2
copy: F/us time us d2

 client i takes F/dmin time


dN Network (with
to download abundant bandwidth)
uN
 NF bits must be
downloaded (aggregate)
 fastest possible upload rate: u +
s ui

dP2P = max { F/us, F/ dmin , NF/(us + ui) }


Server-client vs. P2P: example
Client upload rate = u, F/u = 1 hour, us = 10u, dmin ≥ us

3.5
P2P
Minimum Distribution Time

3
Client-Server
2.5

1.5

0.5

0
0 5 10 15 20 25 30 35

N
2: Application Layer 127
File distribution: BitTorrent
 P2P file distribution

tracker: tracks peers torrent: group of


participating in torrent peers exchanging
chunks of a file

obtain list
of peers

trading
chunks

peer

2: Application Layer 128


BitTorrent (1)
 file divided into 256KB chunks.
 peer joining torrent:
 has no chunks, but will accumulate them over time
 registers with tracker to get list of peers,
connects to subset of peers (“neighbors”)
 while downloading, peer uploads chunks to other
peers.
 peers may come and go
 once peer has entire file, it may (selfishly) leave or
(altruistically) remain
2: Application Layer 129
BitTorrent (2)
Pulling Chunks
 at any given time, different peers have different
subsets of file chunks
 periodically, a peer (Alice) asks each neighbor for
list of chunks that they have.
Two important decision
 which chunks should she request first from her
neighbors?
 To which of her neighbors should she send
requested chunks?
 Alice sends requests for her missing chunks
 rarest first
2: Application Layer 130
BitTorrent (2) Sending Chunks: tit-for-tat
 Alice sends chunks to four
Clever trading algorithm
neighbors currently
Alice gives priority to the sending her chunks at the
neighbors that are highest rate
currently supplying her
 re-evaluate top 4 every
data at the highest
rate. 10 secs
 every 30 secs: randomly
Measures the rate
determines four peers select another peer,
starts sending chunks
Four peers- unchoked
 newly chosen peer may
join top 4
 “optimistically unchoke”

2: Application Layer 131


BitTorrent: Tit-for-tat
(1) Alice “optimistically unchokes” Bob
(2) Alice becomes one of Bob’s top-four providers; Bob reciprocates
(3) Bob becomes one of Alice’s top-four providers

With higher upload rate,


can find better trading
partners & get file faster!
2: Application Layer 132
Distributed Hash Table (DHT)
 DHT = distributed P2P database
 Database has (key, value) pairs;
 key: ss number; value: human name
 key: content type; value: IP address
 (156-45-7081,Johnny Wu)
 (Led Zeppelin IV, 128.17.123.38)

 Peers query DB with key


 DB returns values that match the key

 Peers can also insert (key, value) peers


Distributed Hash Table
 Distributed, P2P database.
 Each peer will only hold a small subset of the
totality of the (key, value) pairs.
 Any peer to query distributed DB
 Any peer insert key value pairs.
 Distributed database- DHT
DHT service
 (Linux, IPBob) and (Linux, IPCharlie)
 Dave, will be responsible for the key “Linux” and
will have the corresponding key-value pairs.
2: Application Layer 134
DHT Identifiers
 Assign integer identifier to each peer in range
[0,2n-1].
 Each identifier can be represented by n bits.
 Require each key to be an integer in same range.
 To get integer keys, hash original key.
 eg, key = h(“Led Zeppelin IV”)
 This is why they call it a distributed “hash” table
How to assign keys to peers?
 Central issue:
 Assigning (key, value) pairs to peers.

 Rule: assign key to the peer that has the


closest ID.
 Convention : closest is the immediate
successor of the key.
 Ex: n=8; peers: 1,3,4,5,8,10,12,14;
 key = 13, then successor peer = 14
 key = 15, then successor peer = 1
Circular DHT (1)
1

3
15

4
12
5
10
8
 Each peeronly aware of immediate successor
and predecessor.
Circle DHT (2)

O(N) messages 1 Who’s resp


on avg to resolve for key 11 ?
I am
query, when there 3
are N peers
15
1110

1110
4
1110

12
1110
1110 5
Define closest 1110

as closest 10
successor 8
Circular DHT with Shortcuts
1 Who’s resp
for key 11?
3
15

4
12
5
10
8
 Each peer keeps track of IP addresses of predecessor,
successor, short cuts.
 Reduced from 6 to 2 messages.
 Possible to design shortcuts so O(log N) neighbors, O(log
N) messages in query
Peer Churn
1
•To handle peer churn, require

15 3 each peer to know the IP address


of its two successors.
• Each peer periodically pings its
4
two successors to see if they
12 are still alive.
5
10
8
 Peer 5 abruptly leaves
 Peer 4 detects; makes 8 its immediate successor;
asks 8 who its immediate successor is; makes 8’s
immediate successor its second successor.
 What if peer 13 wants to join?
Socket programming
Goal: learn how to build client/server application that
communicate using sockets

Socket API socket


 introduced in BSD4.1 UNIX,
1981 a host-local,
 explicitly created, used, application-created,
released by apps
OS-controlled interface
 client/server paradigm
(a “door”) into which
application process can
 two types of transport service
both send and
via socket API: receive messages to/from
 unreliable datagram
another application
 reliable, byte stream- process
oriented

2: Application Layer 141


Socket programming: Creating
Network Applications
 A typical network application consists of a
pair of programs—
 a client program
 a server program

 A client process and a server process are


created, and these processes communicate
 Two types of Network application
 Open –rules dictated by RFC
 Proprietary

2: Application Layer 142


Socket programming with udp

UDP: no “connection” between


client and server
 no handshaking
 sender explicitly attaches application viewpoint
IP address and port no of
destination to each packet UDP provides unreliable transfer
of groups of bytes (“datagrams”)
 server must extract IP
between client and server
address, port of sender
from received packet
UDP: transmitted data may be
received out of order, or
lost

2: Application Layer 143


Example
 1. The 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
the 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: Application Layer 144


 Server must be ready and running— that is,
it must be running as a process before the
client sends its message.
 UDPClient.py.
 UDPServer.py.

2: Application Layer 145


2: Application Layer 146
UDPClient.py
from socket import *
serverName = ‘hostname’
serverPort = 12000
clientSocket = socket(socket.AF_INET,
socket.SOCK_DGRAM)
message = raw_input(’Input lowercase sentence:’)
clientSocket.sendto(message,(serverName, serverPort))
modifiedMessage, serverAddress =
clientSocket.recvfrom(2048)
print modifiedMessage
clientSocket.close()

2: Application Layer 147


UDPClient.py
from socket import *
 The socket module forms the basis of all network
communications in Python
serverName = ‘hostname’
serverPort = 12000
 Ip address of the server or hostname ( eg:
cis.poly.edu)
clientSocket = socket(socket.AF_INET,
socket.SOCK_DGRAM)
creates the client’s socket, called clientSocket. the address
family-AF_INET indicates that the underlying network is using
IPv4.
SOCK_DGRAM, which means it is a UDP socket (rather than a
TCP socket).

2: Application Layer 148


message = raw_input(’Input lowercase
sentence:’)
 raw_input() is a built-in function in Python.
clientSocket.sendto(message,(serverName,
serverPort))
 the method sendto() attaches the
destination address (serverName,
serverPort) to the message and sends the
resulting packet into the process’s socket,
clientSocket.

2: Application Layer 149


 modifiedMessage, serverAddress =
clientSocket.recvfrom(2048)

 print modifiedMessage

 clientSocket.close()

2: Application Layer 150


UDPserver.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind((’’, serverPort))
print ”The server is ready to receive”
while 1:
message, clientAddress =
serverSocket.recvfrom(2048) modifiedMessage =
message.upper()
serverSocket.sendto(modifiedMessage,
clientAddress)

2: Application Layer 151


Socket-programming using TCP
Socket: a door between application process and end-end-
transport protocol (UCP or TCP)
TCP service: reliable transfer of bytes from one process
to another

controlled by
controlled by process application
application process
developer
developer socket socket
controlled by TCP with TCP with controlled by
buffers, operating
operating buffers, internet system
system variables variables

host or host or
server server

2: Application Layer 152


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

2: Application Layer 153


Socket programming with TCP
 connection-oriented protocol.
 Three way handshake and establish a TCPconnection.
 During the three-way handshake, the client process
knocks on the welcoming door of the server
process.
 When the server “hears” the knocking, it creates a
new door— more precisely, a new socket that is
dedicated to that particular client.
 the welcoming door - serverSocket;
 the newly created socket dedicated to the client
making the connection is called connectionSocket

2: Application Layer 154


Socket programming with TCP

2: Application Layer 155


2: Application Layer 156
TCPClient.py
from socket import *
serverName = ’servername’
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input(‘Input lowercase sentence:’)
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print ‘From Server:’, modifiedSentence
clientSocket.close()

2: Application Layer 157


Tcpserver.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind((‘’,serverPort))
serverSocket.listen(1)
print ‘The server is ready to receive’
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
2: Application Layer 158
2: Application Layer 159

You might also like