+ All Categories
Home > Documents > Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... ·...

Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... ·...

Date post: 06-Jan-2020
Category:
Upload: others
View: 5 times
Download: 0 times
Share this document with a friend
29
1 Chapter 2 Application Layer Computer Networking: A Top Down Approach, 4 th diti A note on the use of these ppt slides: We’re making these slides freely available to all (faculty, students, readers). They’re in PowerPoint form so you can add, modify, and delete slides (including this one) and slide content to suit your needs. They obviously represent a lot of work on our part. In return for use, we only ask the following: 2: Application Layer 1 4 th edition. Jim Kurose, Keith Ross Addison-Wesley, July 2007. following: If you use these slides (e.g., in a class) in substantially unaltered form, that you mention their source (after all, we’d like people to use our book!) If you post any slides in substantially unaltered form on a www site, that you note that they are adapted from (or perhaps identical to) our slides, and note our copyright of this material. Thanks and enjoy! JFK/KWR All material copyright 1996-2007 J.F Kurose and K.W. Ross, All Rights Reserved Chapter 2: Application layer 2.1 Principles of network applications 2.6 P2P Applications 2 7 Socket programming network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2: Application Layer 2 Chapter 2: Application Layer Our goals: conceptual, l learn about protocols by examining popular li i l l implementation aspects of network application protocols transport-layer service models client-server application-level protocols HTTP FTP SMTP / POP3 / IMAP DNS i t k 2: Application Layer 3 paradigm peer-to-peer paradigm programming network applications socket API Some network apps e-mail web voice over IP real-time video web instant messaging remote login P2P file sharing multi-user network games real-time video conferencing grid computing 2: Application Layer 4 streaming stored video clips
Transcript
Page 1: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

1

Chapter 2Application Layer

Computer Networking: A Top Down Approach, 4th diti

A note on the use of these ppt slides:We’re making these slides freely available to all (faculty, students, readers). They’re in PowerPoint form so you can add, modify, and delete slides (including this one) and slide content to suit your needs. They obviously represent a lot of work on our part. In return for use, we only ask the following:

2: Application Layer 1

4th edition. Jim Kurose, Keith RossAddison-Wesley, July 2007.

following:If you use these slides (e.g., in a class) in substantially unaltered form,

that you mention their source (after all, we’d like people to use our book!)If you post any slides in substantially unaltered form on a www site, that

you note that they are adapted from (or perhaps identical to) our slides, and note our copyright of this material.

Thanks and enjoy! JFK/KWR

All material copyright 1996-2007J.F Kurose and K.W. Ross, All Rights Reserved

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P Applications2 7 Socket programming network applications

2.2 Web and HTTP2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP

2: Application Layer 2

Chapter 2: Application LayerOur goals:

conceptual, l

learn about protocols by examining popular

li i l l implementation aspects of network application protocols

transport-layer service modelsclient-server

application-level protocols

HTTPFTPSMTP / POP3 / IMAPDNS

i t k

2: Application Layer 3

paradigmpeer-to-peer paradigm

programming network applications

socket API

Some network apps

e-mailweb

voice over IPreal-time video web

instant messagingremote loginP2P file sharingmulti-user network games

real-time video conferencinggrid computing

2: Application Layer 4

gstreaming stored video clips

Page 2: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

2

Creating a network appwrite programs that

run on (different) end s st ms

applicationtransportnetworkdata linkphysical

systemscommunicate over networke.g., web server software communicates with browser software

little software written for devices in network core application

transport

applicationtransportnetworkdata linkphysical

2: Application Layer 5

network core devices do not run user applications applications on end systems allows for rapid app development, propagation

pnetworkdata linkphysical

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P file sharing2 7 Socket programming network applications

2.2 Web and HTTP2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

2: Application Layer 6

Application architectures

Client-serverP t (P2P)Peer-to-peer (P2P)Hybrid of client-server and P2P

2: Application Layer 7

Client-server architectureserver:

always-on hostpermanent IP addressserver farms for scaling

clients:communicate with servermay be intermittently

client/server

2: Application Layer 8

may be intermittently connectedmay have dynamic IP addressesdo not communicate directly with each other

Page 3: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

3

Pure P2P architecture

no always-on serverarbitrary end systems arbitrary end systems directly communicatepeers are intermittently connected and change IP addressesexample: Gnutella

peer-peer

2: Application Layer 9

Highly scalable but difficult to manage

Hybrid of client-server and P2PSkype

voice-over-IP P2P applicationcentralized server: finding address of remote centralized server: finding address of remote party: client-client connection: direct (not through server)

Instant messagingchatting between two users is P2Pcentralized service: client presence detection/location

2: Application Layer 10

detection/location• user registers its IP address with central

server when it comes online• user contacts central server to find IP

addresses of buddies

Processes communicating

Process: program running within a host.

Client process: process that initiates

within same host, two processes communicate using inter-process communication (defined by OS).processes in different

communicationServer process: process

that waits to be contacted

Note: applications with

2: Application Layer 11

processes in different hosts communicate by exchanging messages

Note applications with P2P architectures have client processes & server processes

Sockets

process sends/receives messages to/from its

host orserver

host orserver

g fsocketsocket analogous to door

sending process shoves message out doorsending process relies on transport infrastructure

th id f d hi h

process

TCP withbuffers,variables

socket

process

TCP withbuffers,variables

socket

Internet

controlled byapp developer

2: Application Layer 12

on other side of door which brings message to socket at receiving process

controlledby OS

API: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later)

Page 4: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

4

Addressing processesto receive messages, process must have identifieridentifierhost device has unique 32-bit IP addressQ: does IP address of host on which process runs suffice for identifying the process?

2: Application Layer 13

identifying the process?

Addressing processesto receive messages, process must have identifier

identifier includes both IP address and port numbers associated with identifier

host device has unique 32-bit IP addressQ: does IP address of host on which process runs suffice for identifying the

numbers associated with process on host.Example port numbers:

HTTP server: 80Mail server: 25

to send HTTP message to gaia cs umass edu web

2: Application Layer 14

identifying the process?

A: No, manyprocesses can be running on same host

to gaia.cs.umass.edu web server:

IP address: 128.119.245.12Port number: 80

more shortly…

App-layer protocol defines

Types of messages exchanged,

Public-domain protocols:defined in RFCsexchanged,

e.g., request, response Message syntax:

what fields in messages & how fields are delineated

Message semantics meaning of information in

defined in RFCsallows for interoperabilitye.g., HTTP, SMTP

Proprietary protocols:e.g., Skype

2: Application Layer 15

meaning of information in fields

Rules for when and how processes send & respond to messages

What transport service does an app need?

Data losssome apps (e.g., audio) can tolerate some loss

Bandwidthsome apps (e.g.,

tolerate some lossother apps (e.g., file transfer, telnet) require 100% reliable data transfer

Timingsome apps (e g

multimedia) require minimum amount of bandwidth to be “effective”other apps (“elastic apps”) make use of

2: Application Layer 16

some apps (e.g., Internet telephony, interactive games) require low delay to be “effective”

whatever bandwidth they get

Page 5: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

5

Transport service requirements of common apps

Application Data loss Bandwidth Time Sensitive

file transfere-mail

Web documentsreal-time audio/video

stored audio/videointeractive games

no lossno lossno lossloss-tolerant

loss-tolerantloss-tolerant

elasticelasticelasticaudio: 5kbps-1Mbpsvideo:10kbps-5Mbpssame as above few kbps up

nononoyes, 100’s msec

yes, few secsyes, 100’s msec

d

2: Application Layer 17

instant messaging no loss elastic yes and no

Internet transport protocols services

TCP service:connection-oriented: setup

UDP service:unreliable data transfer connection oriented: setup

required between client and server processesreliable transport between sending and receiving processflow control: sender won’t overwhelm receiver congestion control: throttle

fbetween sending and receiving processdoes not provide: connection setup, reliability, flow control, congestion control, timing, or bandwidth guarantee

2: Application Layer 18

congestion control: throttle sender when network overloadeddoes not provide: timing, minimum bandwidth guarantees

Q: why bother? Why is there a UDP?

Internet apps: application, transport protocols

ApplicationApplicationlayer protocol

Underlyingtransport protocol

e-mailremote terminal access

Web file transfer

streaming multimedia

Internet telephony

SMTP [RFC 2821]Telnet [RFC 854]HTTP [RFC 2616]FTP [RFC 959]proprietary(e.g. RealNetworks)proprietary

TCPTCPTCPTCPTCP or UDP

2: Application Layer 19

(e.g., Vonage,Dialpad) typically UDP

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P file sharing2 7 Socket programming network applications

app architecturesapp requirements

2.2 Web and HTTP2.4 Electronic Mail

SMTP, POP3, IMAP2 5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP

2: Application Layer 20

2.5 DNS

Page 6: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

6

Web and HTTP

First some jargonWeb page consists of objectsWeb page consists of objectsObject can be HTML file, JPEG image, Java applet, audio file,…Web page consists of base HTML-file which includes several referenced objectsEach object is addressable by a URL

2: Application Layer 21

Example URL:www.someschool.edu/someDept/pic.gif

host name path name

HTTP overview

HTTP: hypertext transfer protocoltransfer protocolWeb’s application layer protocolclient/server model

client: browser that requests, receives, “displays” Web objectsserver: Web server

PC runningExplorer

Server running

Apache Web

2: Application Layer 22

server: Web server sends objects in response to requests

HTTP 1.0: RFC 1945HTTP 1.1: RFC 2068

p Wserver

Mac runningNavigator

HTTP overview (continued)

Uses TCP:client initiates TCP

HTTP is “stateless”server maintains no client initiates TCP

connection (creates socket) to server, port 80server accepts TCP connection from clientHTTP messages (application-layer protocol messages) exchanged between browser

minformation about past client requests

Protocols that maintain “state” are complex!past history (state) must be maintained

aside

2: Application Layer 23

exchanged between browser (HTTP client) and Web server (HTTP server)TCP connection closed

be maintainedif server/client crashes, their views of “state” may be inconsistent, must be reconciled

HTTP connections

Nonpersistent HTTPAt most one object is

Persistent HTTPMultiple objects can At most one object is

sent over a TCP connection.HTTP/1.0 uses nonpersistent HTTP

Multiple objects can be sent over single TCP connection between client and server.HTTP/1.1 uses persistent connections

2: Application Layer 24

persistent connections in default mode

Page 7: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

7

Nonpersistent HTTPSuppose user enters URL

www.someSchool.edu/someDepartment/home.index

1a HTTP client initiates TCP

(contains text, references to 10

jpeg images)

1a. HTTP client initiates TCP connection to HTTP server (process) at www.someSchool.edu on port 80

2. HTTP client sends HTTP request message (containing URL) into TCP connection

1b. HTTP server at host www.someSchool.edu waiting for TCP connection at port 80. “accepts” connection, notifying client

3 HTTP server receives request

2: Application Layer 25

URL) into TCP connection socket. Message indicates that client wants object someDepartment/home.index

3. HTTP server receives request message, forms response message containing requested object, and sends message into its socket

time

Nonpersistent HTTP (cont.)

5 HTTP client receives response

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

6. Steps 1-5 repeated for each of 10 jpeg objects

time

2: Application Layer 26

Non-Persistent HTTP: Response time

Definition of RTT: time to send a small packet to travel from client to travel from client to server and back.

Response time:one RTT to initiate TCP connectionone RTT for HTTP

st d fi st f

time to transmit file

initiate TCPconnection

RTTrequestfile

RTT

fil

2: Application Layer 27

request and first few bytes of HTTP response to returnfile transmission time

total = 2RTT+transmit time

filereceived

time time

Persistent HTTP

Nonpersistent HTTP issues:requires 2 RTTs per objectOS h d f h TCP

Persistent without pipelining:client issues new request only when previous OS overhead for each TCP

connectionbrowsers often open parallel TCP connections to fetch referenced objects

Persistent HTTPserver leaves connection

f di

only when previous response has been receivedone RTT for each referenced object

Persistent with pipelining:default in HTTP/1.1client sends requests as

it t

2: Application Layer 28

open after sending responsesubsequent HTTP messages between same client/server sent over open connection

soon as it encounters a referenced objectas little as one RTT for all the referenced objects

Page 8: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

8

HTTP request message

two types of HTTP messages: request, responseHTTP request message:HTTP request message:

ASCII (human-readable format)

GET /somedir/page.html HTTP/1.1Host: www.someschool.edu User-agent: Mozilla/4.0Connection: close

request line(GET, POST,

HEAD commands)

header

2: Application Layer 29

Connection: close Accept-language:fr

(extra carriage return, line feed)

lines

Carriage return, line feed

indicates end of message

HTTP request message: general format

2: Application Layer 30

Uploading form input

Post method:Web page often Web page often includes form inputInput is uploaded to server in entity body

URL method:Uses GET methodInput is uploaded in URL field of request line:

2: Application Layer 31

www.somesite.com/animalsearch?monkeys&banana

Method types

HTTP/1.0GET

HTTP/1.1GET POST HEADGET

POSTHEAD

asks server to leave requested object out of response

GET, POST, HEADPUT

uploads file in entity body to path specified in URL field

DELETEdeletes file specified in

2: Application Layer 32

deletes file specified in the URL field

Page 9: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

9

HTTP response message

HTTP/1.1 200 OK

status line(protocol

status code /Connection closeDate: Thu, 06 Aug 1998 12:00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Jun 1998 …... Content-Length: 6821 Content-Type: text/html

d t d t d t d t d t

status codestatus phrase)

headerlines

data e g

2: Application Layer 33

data data data data data ... data, e.g., requestedHTML file

HTTP response status codesIn first line in server->client response message.A few sample codes:200 OK

request succeeded, requested object later in this message301 Moved Permanently

requested object moved, new location specified later in this message (Location:)

400 Bad Request

2: Application Layer 34

qrequest message not understood by server

404 Not Foundrequested document not found on this server

505 HTTP Version Not Supported

Trying out HTTP (client side) for yourself

1. Telnet to your favorite Web server:O TCP ti t t 80Opens TCP connection to port 80(default HTTP server port) at cis.poly.edu.Anything typed in sent to port 80 at cis.poly.edu

telnet cis.poly.edu 80

2. Type in a GET HTTP request:GET /~ross/ HTTP/1.1H t i l d

By typing this in (hit carriagereturn twice) you send

2: Application Layer 35

Host: cis.poly.edu return twice), you sendthis minimal (but complete) GET request to HTTP server

3. Look at response message sent by HTTP server!

Let’s look at HTTP in action

telnet exampleEth l lEthereal example

2: Application Layer 36

Page 10: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

10

User-server state: cookies

Many major Web sites use cookies

Example:Susan always access

Four components:1) cookie header line of

HTTP response message2) cookie header line in

HTTP request message3) cookie file kept on

user’s host, managed by ’ b

Internet always from PCvisits specific e-commerce site for first timewhen initial HTTP requests arrives at site,

2: Application Layer 37

user’s browser4) back-end database at

Web site

qsite creates:

unique IDentry in backend database for ID

Cookies: keeping “state” (cont.)client server

ebay 8734usual http request msg

usual http response msg

cookie file

one week later:

usual http request msgcookie: 1678 cookie-

specificaction

access

usual http request msg Amazon servercreates ID

1678 for user createentry

usual http response Set-cookie: 1678

ebay 8734amazon 1678

backend

2: Application Layer 38

p p g

usual http response msg

on w at r action

usual http request msgcookie: 1678 cookie-

spectificaction

accessebay 8734amazon 1678

database

Cookies (continued)What cookies can bring:

authorizationCookies and privacy:

cookies permit sites to

aside

shopping cartsrecommendationsuser session state (Web e-mail)

learn a lot about youyou may supply name and e-mail to sites

How to keep “state”:

2: Application Layer 39

protocol endpoints: maintain state at sender/receiver over multiple transactionscookies: http messages carry state

Web caches (proxy server)

user sets browser:

Goal: satisfy client request without involving origin server

origin user sets browser Web accesses via cachebrowser sends all HTTP requests to cache

object in cache: cache

client

Proxyserver

gserver

2: Application Layer 40

object in cache cache returns object else cache requests object from origin server, then returns object to client

clientorigin server

Page 11: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

11

More about Web caching

cache acts as both client and server

Why Web caching?reduce response time client and server

typically cache is installed by ISP (university, company, residential ISP)

reduce response time for client requestreduce traffic on an institution’s access link.Internet dense with caches: enables “poor”

2: Application Layer 41

caches: enables poor content providers to effectively deliver content (but so does P2P file sharing)

Caching example Assumptions

average object size = 100,000 bits

originservers

publicbitsavg. request rate from institution’s browsers to origin servers = 15/secdelay from institutional router to any origin server and back to router = 2 sec

C

pInternet

institutionalnetwork 10 Mbps LAN

1.5 Mbps access link

2: Application Layer 42

Consequencesutilization on LAN = 15%utilization on access link = 100%total delay = Internet delay + access delay + LAN delay

= 2 sec + sec + milliseconds

p

institutionalcache

Caching example (cont)possible solution

increase bandwidth of access link to say 10 Mbps

originservers

publiclink to, say, 10 Mbpsconsequence

utilization on LAN = 15%utilization on access link = 15%Total delay = Internet delay + access delay + LAN delay

= 2 sec + msecs + msecs

pInternet

institutionalnetwork 10 Mbps LAN

10 Mbps access link

2: Application Layer 43

often a costly upgradep

institutionalcache

Caching example (cont)

possible solution: install cache

h 0 4

originservers

publicsuppose hit rate is 0.4

consequence40% requests will be satisfied almost immediately60% requests satisfied by origin serverutilization of access link reduced to 60%, resulting in

li ibl d l ( 10

pInternet

institutionalnetwork 10 Mbps LAN

1.5 Mbps access link

2: Application Layer 44

negligible delays (say 10 msec)total avg delay = Internet delay + access delay + LAN delay = .6*(2.01) secs + .4*milliseconds < 1.4 secs

p

institutionalcache

Page 12: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

12

Conditional GET

Goal: don’t send object if cache has up-to-date cached

cache serverHTTP request msg

versioncache: specify date of cached copy in HTTP requestIf-modified-since:

<date>

server: response contains no object if cached copy is up-t d t

q gIf-modified-since:

<date>

HTTP responseHTTP/1.0

304 Not Modified

object not

modified

HTTP request msg

2: Application Layer 45

to-date: HTTP/1.0 304 Not

Modified

HTTP request msgIf-modified-since:

<date>

HTTP responseHTTP/1.0 200 OK

<data>

object modified

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P file sharing2 7 Socket programming network applications

2.2 Web and HTTP2.3 FTP2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

2: Application Layer 46

FTP: the file transfer protocol

file transfer FTPFTPuser

FTP

transfer file to/from remote hostclient/server model

li t id th t i iti t t f ( ith t /f

serveruserinterface

client

local filesystem

remote filesystem

user at host

2: Application Layer 47

client: side that initiates transfer (either to/from remote)server: remote host

ftp: RFC 959ftp server: port 21

FTP: separate control, data connections

FTP client contacts FTP server at port 21, TCP is transport

TCP control connectionport 21

p pprotocolclient authorized over control connectionclient browses remote directory by sending commands over control connection.when server receives file

FTPclient

FTPserver

TCP data connectionport 20

server opens another TCP data connection to transfer another file.control connection: “out of

2: Application Layer 48

transfer command, server opens 2nd TCP connection (for file) to clientafter transferring one file, server closes data connection.

control connection: out of band”FTP server maintains “state”: current directory, earlier authentication

Page 13: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

13

FTP commands, responses

Sample commands:sent as ASCII text over

Sample return codesstatus code and phrase (as sent as ASCII text over

control channelUSER usernamePASS password

LIST return list of file in current directoryRETR filename retrieves

status code and phrase (as in HTTP)331 Username OK, password required125 data connection already open; transfer starting425 Can’t open data

2: Application Layer 49

(gets) fileSTOR filename stores (puts) file onto remote host

425 Can t open data connection452 Error writing file

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P file sharing2 7 Socket programming network applications

2.2 Web and HTTP2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

2: Application Layer 50

Electronic Mail

Three major components:user agents

user mailbox

outgoing message queue

mail

useragent

user agents mail servers simple mail transfer protocol: SMTP

User Agenta.k.a. “mail reader”composing editing reading

mailserver

useragent

useragent

usermail

mailserver

SMTP

SMTP

SMTP

2: Application Layer 51

composing, editing, reading mail messagese.g., Eudora, Outlook, elm, Mozilla Thunderbirdoutgoing, incoming messages stored on server

agentmail

server

useragent

useragent

Electronic Mail: mail servers

Mail Serversmailbox contains incoming il

useragent

mailbox contains incoming messages for usermessage queue of outgoing (to be sent) mail messagesSMTP protocol between mail servers to send email messages

client: sending mail

mailserver

useragent

useragent

usermail

mailserver

SMTP

SMTP

SMTP

2: Application Layer 52

client: sending mail server“server”: receiving mail server

us ragent

mailserver

useragent

useragent

Page 14: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

14

Electronic Mail: SMTP [RFC 2821]

uses TCP to reliably transfer email message from client to server, port 25direct transfer: sending server to receiving serverthree phases of transfer

handshaking (greeting)transfer of messagesclosure

command/response interactiond ASCII

2: Application Layer 53

commands: ASCII textresponse: status code and phrase

messages must be in 7-bit ASCII

Scenario: Alice sends message to Bob1) Alice uses UA to compose

message and “to” [email protected]

2) Ali ’s UA s nds m ss

4) SMTP client sends Alice’s message over the TCP connection

5) Bob’s mail server places the 2) Alice s UA sends message to her mail server; message placed in message queue

3) Client side of SMTP opens TCP connection with Bob’s mail server

5) Bob s mail server places the message in Bob’s mailbox

6) Bob invokes his user agent to read message

2: Application Layer 54

useragent

mailserver

mailserver user

agent

1

2 3 4 56

Sample SMTP interactionS: 220 hamburger.edu C: HELO crepes.fr S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: <[email protected]> S: 250 [email protected]... Sender ok C: RCPT TO: <[email protected]> S: 250 [email protected] ... Recipient ok C: DATA S: 354 Enter mail, end with "." on a line by itself C: Do you like ketchup? C: How about pickles?

2: Application Layer 55

C: How about pickles? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger.edu closing connection

Try SMTP interaction for yourself:

telnet servername 25

see 220 reply from serversee 220 reply from serverenter HELO, MAIL FROM, RCPT TO, DATA, QUIT commands

above lets you send email without using email client (reader)

2: Application Layer 56

Page 15: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

15

SMTP: final words

SMTP uses persistent connections

Comparison with HTTP:HTTP: pullSMTP requires message

(header & body) to be in 7-bit ASCIISMTP server uses CRLF.CRLF to determine end of message

HTTP: pullSMTP: push

both have ASCII command/response interaction, status codes

HTTP: each object l t d i it

2: Application Layer 57

encapsulated in its own response msgSMTP: multiple objects sent in multipart msg

Mail message format

SMTP: protocol for exchanging email msgs header

blankRFC 822: standard for text message format:header lines, e.g.,

To:From:Subject:

different from SMTP

body

blankline

2: Application Layer 58

commands!body

the “message”, ASCII characters only

Message format: multimedia extensions

MIME: multimedia mail extension, RFC 2045, 2056additional lines in msg header declare MIME content typetype

From: [email protected] To: [email protected] Subject: Picture of yummy crepe. MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Type: image/jpeg multimedia data

method usedto encode data

MIME version

2: Application Layer 59

base64 encoded data ..... ......................... ......base64 encoded data

multimedia datatype, subtype,

parameter declaration

encoded data

Mail access protocols

useragentuser

agent

SMTP SMTP accessprotocol

SMTP: delivery/storage to receiver’s serverMail access protocol: retrieval from server

POP: Post Office Protocol [RFC 1939]• authorization (agent <-->server) and download

sender’s mail server

g

receiver’s mail server

2: Application Layer 60

authorization (agent < >server) and download IMAP: Internet Mail Access Protocol [RFC 1730]

• more features (more complex)• manipulation of stored msgs on server

HTTP: gmail, Hotmail, Yahoo! Mail, etc.

Page 16: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

16

POP3 protocol

authorization phaseclient commands:

S: +OK POP3 server ready C: user bob S: +OK C: pass hungry S: +OK user successfully logged on

user: declare usernamepass: password

server responses+OK-ERR

transaction phase, client:l

C: list S: 1 498 S: 2 912 S: . C: retr 1 S: <message 1 contents>S: . C: dele 1

2: Application Layer 61

list: list message numbersretr: retrieve message by numberdele: deletequit

:C: retr 2 S: <message 1 contents>S: . C: dele 2 C: quit S: +OK POP3 server signing off

POP3 (more) and IMAPMore about POP3

Previous example uses “d l d d d l t ”

IMAPKeep all messages in

l h “download and delete” mode.Bob cannot re-read e-mail if he changes client“Download-and-keep”:

one place: the serverAllows user to organize messages in foldersIMAP keeps user state across sessions:

2: Application Layer 62

copies of messages on different clientsPOP3 is stateless across sessions

names of folders and mappings between message IDs and folder name

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P file sharing2 7 Socket programming network applications

2.2 Web and HTTP2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

2: Application Layer 63

DNS: Domain Name System

People: many identifiers:SSN name passport #

Domain Name System:distributed databaseSSN, name, passport #

Internet hosts, routers:IP address (32 bit) -used for addressing datagrams“name”, e.g., ww.yahoo.com - used by hum ns

distributed databaseimplemented in hierarchy of many name serversapplication-layer protocolhost, routers, name servers to communicate to resolve names (address/name translation)

note: core Internet

2: Application Layer 64

humansQ: map between IP

addresses and name ?

note core Internet function, implemented as application-layer protocolcomplexity at network’s “edge”

Page 17: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

17

DNS Why not centralize DNS?

single point of failureDNS services

hostname to IP ptraffic volumedistant centralized databasemaintenance

d ’t l !

maddress translationhost aliasing

Canonical, alias namesmail server aliasingload distribution

replicated Web

2: Application Layer 65

doesn’t scale!replicated Web servers: set of IP addresses for one canonical name

Root DNS Servers

DNS org DNS servers edu DNS servers

Distributed, Hierarchical Database

com DNS servers org DNS servers edu DNS servers

poly.eduDNS servers

umass.eduDNS serversyahoo.com

DNS serversamazon.comDNS servers

pbs.orgDNS servers

Client wants IP for www.amazon.com; 1st approx:client queries a root server to find com DNS server

2: Application Layer 66

client queries com DNS server to get amazon.com DNS serverclient queries amazon.com DNS server to get IP address for www.amazon.com

DNS: Root name serverscontacted by local name server that can not resolve nameroot name server:

contacts authoritative name server if name mapping not knowncontacts authoritative name server if name mapping not knowngets mappingreturns mapping to local name server

e NASA Mt View, CAf I t t S ft C P l Alt

i Autonomica, Stockholm (plus 28 other locations)

k RIPE London (also 16 other locations)

m WIDE Tokyo (also Seoul, Paris SF)

a Verisign, Dulles, VAc Cogent, Herndon, VA (also LA)d U Maryland College Park, MDg US DoD Vienna, VAh ARL Aberdeen, MDj Verisign, ( 21 locations)

2: Application Layer 67

13 root name servers worldwide

b USC-ISI Marina del Rey, CAl ICANN Los Angeles, CA

f Internet Software C. Palo Alto, CA (and 36 other locations)

Paris, SF)

TLD and Authoritative Servers

Top-level domain (TLD) servers:responsible for com org net edu etc and all responsible for com, org, net, edu, etc, and all top-level country domains uk, fr, ca, jp.Network Solutions maintains servers for com TLDEducause for edu TLD

Authoritative DNS servers:organization’s DNS servers, providing authoritative hostname to IP mappings for

2: Application Layer 68

authoritative hostname to IP mappings for organization’s servers (e.g., Web, mail).can be maintained by organization or service provider

Page 18: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

18

Local Name Server

does not strictly belong to hierarchyh ISP ( id ti l ISP 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

t f d i t hi h

2: Application Layer 69

acts as proxy, forwards query into hierarchy

root DNS server

23

4TLD DNS server

DNS name resolution example

Host at cis.poly.edu wants IP address for

local DNS serverdns.poly.edu

1

4

5

6

authoritative DNS server

78

wants IP address for gaia.cs.umass.edu

iterated query:contacted server replies with name of server to contact

2: Application Layer 70

requesting hostcis.poly.edu

gaia.cs.umass.edu

authoritative DNS serverdns.cs.umass.edu“I don’t know this

name, but ask this server”

root DNS server

2 3recursive query:puts burden of name

DNS name resolution example

local DNS serverdns.poly.edu

1

45

67

8

TLD DNS server

puts burden of name resolution on contacted name serverheavy load?

2: Application Layer 71

requesting hostcis.poly.edu

gaia.cs.umass.edu

authoritative DNS serverdns.cs.umass.edu

DNS: caching and updating records

once (any) name server learns mapping, it cachesmapping

cache entries timeout (disappear) after some timeTLD servers typically cached in local name servers

• Thus root name servers not often visitedupdate/notify mechanisms under design by IETF

2: Application Layer 72

p fy g yRFC 2136http://www.ietf.org/html.charters/dnsind-charter.html

Page 19: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

19

DNS recordsDNS: distributed db storing resource records (RR)

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

Type=NSname is domain (e g

yp

Type=Aname is hostnamevalue is IP address

Type=CNAMEname is alias name for some “canonical” (the real) namewww.ibm.com is reallyservereast.backup2.ibm.com

l

2: Application Layer 73

name is domain (e.g. foo.com)value is hostname of authoritative name server for this domain

value is canonical name

Type=MXvalue is name of mailserver associated with name

DNS protocol, messagesDNS protocol : query and reply messages, both with

same message format

msg headeridentification: 16 bit # for query, reply to query uses same #flags:

query or reply

2: Application Layer 74

recursion desired recursion availablereply is authoritative

DNS protocol, messages

Name, type fieldsf for a query

RRs in responseto query

records forauthoritative servers

2: Application Layer 75

additional “helpful”info that may be used

Inserting records into DNSexample: new startup “Network Utopia”register name networkuptopia.com at DNS registrar( k l )

g p p g(e.g., Network Solutions)

provide names, IP addresses of authoritative name server (primary and secondary)registrar inserts two RRs into com TLD server:

(networkutopia.com, dns1.networkutopia.com, NS)(dns1.networkutopia.com, 212.212.212.1, A)

2: Application Layer 76

create authoritative server Type A record for www.networkuptopia.com; Type MX record for networkutopia.comHow do people get IP address of your Web site?

Page 20: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

20

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P file sharing2 7 Socket programming network applications

app architecturesapp requirements

2.2 Web and HTTP2.4 Electronic Mail

SMTP, POP3, IMAP2 5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

2: Application Layer 77

2.5 DNS

P2P file sharing

ExampleAlice runs P2P client

Alice chooses one of the peers, Bob.file is copied from Alice runs P2P client

application on her notebook computerintermittently connects to Internet; gets new IP address for each connection

pBob’s PC to Alice’s notebook: HTTPwhile Alice downloads, other users uploading from Alice.Alice’s peer is both a

2: Application Layer 78

for each connectionasks for “Hey Jude”application displays other peers that have copy of Hey Jude.

Alice s peer is both a Web client and a transient Web server.

All peers are servers = highly scalable!

P2P: centralized directory

original “Napster” design1) when peer connects it

centralizeddirectory server

Bob

1) when peer connects, it informs central server:

IP addresscontent

2) Alice queries for “Hey Jude”

3) Alice requests file from

y

peers1

1

1

12

3

2: Application Layer 79

3) Alice requests file from Bob

Alice

P2P: problems with centralized directory

single point of failureperformance bottleneck

file transfer is decentralized, but performance bottleneck

copyright infringement: “target” of lawsuit is obvious

decentralized, but locating content is highly centralized

2: Application Layer 80

Page 21: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

21

Query flooding: Gnutella

fully distributedno central server

overlay network: graphedge between peer X

public domain protocolmany Gnutella clients implementing protocol

edge between peer X and Y if there’s a TCP connectionall active peers and edges form overlay netedge: virtual (notphysical) link

2: Application Layer 81

physical) linkgiven peer typically connected with < 10 overlay neighbors

Gnutella: protocol

Q

File transfer:HTTPQuery message

sent over existing TCPconnections

Query

QueryQueryHitpeers forward

Query messageQueryHit

sent over reversepath

2: Application Layer 82

QueryHitp

Scalability:limited scopeflooding

Gnutella: Peer joining

1. joining peer Alice must find another peer in Gnutella network: use list of candidate peersp

2. Alice sequentially attempts TCP connections with candidate peers until connection setup with Bob

3. Flooding: Alice sends Ping message to Bob; Bob forwards Ping message to his overlay neighbors (who then forward to their neighbors….)

peers receiving Ping message respond to Alice ith P

2: Application Layer 83

with Pong message4. Alice receives many Pong messages, and can then

setup additional TCP connectionsPeer leaving: see homework problem!

Hierarchical Overlay

between centralized index, query flooding index, query flooding approacheseach peer is either a group leader or assigned to a group leader.

TCP connection between peer and its group leader.

2: Application Layer 84

p g pTCP connections between some pairs of group leaders.

group leader tracks content in its children

ordinary peer

group-leader peer

neighoring relationshipsin overlay network

Page 22: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

22

Comparing Client-server, P2P architecturesQuestion : How much time distribute file

initially at one server to N other computers?

us

u2d1 d2u1

Server

File, size F

us: server upload bandwidthui: client/peer i upload bandwidth

di: client/peer i download bandwidth

2: Application Layer 85

uN

dN Network (with abundant bandwidth)

Client-server: file distribution time

uu2d1 d2

u1

Server

Fserver sequentially sends N copies: us 2

uN

dNNetwork (with abundant bandwidth)

sends N copies:NF/us time

client i takes F/di time to download

2: Application Layer 86

increases linearly in N(for large N)

= dcs = max { NF/us, F/min(di) }i

Time to distribute Fto N clients using

client/server approach

P2P: file distribution time

uu2d1 d2

u1

Server

Fserver must send one copy: F/us time us 2

uN

dNNetwork (with abundant bandwidth)

copy: F/us time client i takes F/di time to downloadNF bits must be downloaded (aggregate)

fastest possible upload rate (assuming all nodes sending file chunks to same

2: Application Layer 87

gpeer): us + Σuii=1,N

dP2P = max { F/us, F/min(di) , NF/(us + Σui) }i i=1,N

3

3.5

e P2P

Comparing Client-server, P2P architectures

0 5

1

1.5

2

2.5

3

Min

imum

Dis

tribu

tion

Tim Client-Server

2: Application Layer 88

0

0.5

0 5 10 15 20 25 30 35

N

M

Page 23: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

23

P2P Case Study: BitTorrent

tracker: tracks peers torrent: group of P2P file distribution

tracker tracks peers participating in torrent

g ppeers exchanging chunks of a file

obtain listof peers

2: Application Layer 89

trading chunks

peer

BitTorrent (1)fil di id d i t 256KB h kfile divided into 256KB chunks.peer joining torrent:

has no chunks, but will accumulate them over timeregisters with tracker to get list of peers, connects to subset of peers (“neighbors”)

while downloading, peer uploads chunks to other

2: Application Layer 90

while downloading, peer uploads chunks to other peers. peers may come and goonce peer has entire file, it may (selfishly) leave or (altruistically) remain

BitTorrent (2)Pulling Chunks

at any given time, Sending Chunks: tit-for-tat

Alice sends chunks to y gdifferent peers have different subsets of file chunksperiodically, a peer (Alice) asks each neighbor for list of

four neighbors currently sending her chunks at the highest rate

re-evaluate top 4 every 10 secs

every 30 secs: randomly

2: Application Layer 91

chunks that they have.Alice issues requests for her missing chunks

rarest first

y yselect another peer, starts sending chunks

newly chosen peer may join top 4

P2P Case study: Skype

P2P (pc-to-pc, pc-to-phone, phone-to-pc)

Skype clients (SC)

phone, phone to pc) Voice-Over-IP (VoIP) application

also IMproprietary application-layer protocol (inferred via

Supernode (SN)

Skype login server

2: Application Layer 92

protocol (inferred via reverse engineering) hierarchical overlay

Page 24: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

24

Skype: making a call

User starts SkypeSC registers with SN

Skype login server

SC registers with SNlist of bootstrap SNs

SC logs in (authenticate)Call: SC contacts SN will callee ID

2: Application Layer 93

SN contacts other SNs (unknown protocol, maybe flooding) to find addr of callee; returns addr to SC

SC directly contacts callee, overTCP

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P file sharing2 7 Socket programming network applications

2.2 Web and HTTP2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP

2: Application Layer 94

Socket programmingGoal: learn how to build client/server application that

communicate using sockets

Socket APIintroduced in BSD4.1 UNIX, 1981explicitly created, used, released by apps client/server paradigm t t f t t

a host-local, application-created,

OS-controlled interface (a “door”) into which

application process can both send and

socket

2: Application Layer 95

two types of transport service via socket API:

unreliable datagram reliable, byte stream-oriented

both send and receive messages to/from

another application process

Socket-programming using TCPSocket: a door between application process and end-

end-transport protocol (UCP or TCP)TCP service: reliable transfer of bytes from one

process to another

processsocket

controlled byapplicationdeveloper

process

TCP withsocket

controlled byapplicationdeveloper

controlled by

2: Application Layer 96

TCP withbuffers,variables

controlled byoperating

system

host orserver

TCP withbuffers,variables

controlled byoperatingsystem

host orserver

internet

Page 25: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

25

Socket programming with TCPClient must contact server

server process must first be running

When contacted by client, server TCP creates new socket for server process to be running

server must have created socket (door) that welcomes client’s contact

Client contacts server by:creating client-local TCP socket

socket for server process to communicate with client

allows server to talk with multiple clientssource port numbers used to distinguish clients (more in Chap 3)

2: Application Layer 97

specifying IP address, port number of server processWhen client creates socket: client TCP establishes connection to server TCP

TCP provides reliable, in-ordertransfer of bytes (“pipe”) between client and server

application viewpoint

Client/server socket interaction: TCP

create socket,port=x, for

Server (running on hostid) Client

wait for incomingconnection requestconnectionSocket =welcomeSocket.accept()

port x, forincoming request:welcomeSocket =

ServerSocket()

create socket,connect to hostid, port=xclientSocket =

Socket()

send request usingli tS k tread request from

TCP connection setup

2: Application Layer 98

closeconnectionSocket

read reply fromclientSocket

closeclientSocket

clientSocketread request fromconnectionSocket

write reply toconnectionSocket

er

keyboard monitor

Stream jargonA stream is a sequence of characters that flow into

erve

r

Serv

er

inFr

omU

se

Process

input

inputstream

output

Clientprocess

or out of a process.An input stream is attached to some input source for the process, e.g., keyboard or socket.An output stream is attached to an output

i

2: Application Layer 99

outT

oSe

to network from network

inFr

omS

clientSocket

inputstream

outputstream

TCPsocket

client TCP socket

source, e.g., monitor or socket.

Socket programming with TCP

Example client-server app:1) client reads line from

d d (standard input (inFromUserstream) , sends to server via socket (outToServerstream)

2) server reads line from socket3) server converts line to

uppercase, sends back to li

2: Application Layer 100

client4) client reads, prints modified

line from socket (inFromServer stream)

Page 26: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

26

Example: Java client (TCP)

import java.io.*; import java.net.*; class TCPClient {class TCPClient {

public static void main(String argv[]) throws Exception {

String sentence; String modifiedSentence;

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

Createinput stream

2: Application Layer 101

Socket clientSocket = new Socket("hostname", 6789);

DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

Create client socket,

connect to serverCreate

output streamattached to socket

Example: Java client (TCP), cont.

BufferedReader inFromServer = B ff dR d (

Createinput stream new BufferedReader(new

InputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();

outToServer.writeBytes(sentence + '\n');

modifiedSentence = inFromServer.readLine();

input streamattached to socket

Send lineto server

Read linefrom server

2: Application Layer 102

System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close();

} }

from server

Example: Java server (TCP)import java.io.*; import java.net.*;

class TCPServer {

public static void main(String argv[]) throws Exception {

String clientSentence; String capitalizedSentence;

ServerSocket welcomeSocket = new ServerSocket(6789);

while(true) {

Createwelcoming socket

at port 6789

Wait, on welcoming

2: Application Layer 103

Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient = new BufferedReader(newInputStreamReader(connectionSocket.getInputStream()));

gsocket for contact

by client

Create inputstream, attached

to socket

Example: Java server (TCP), cont

DataOutputStream outToClient =Create output

stream, attached DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence); }

Read in linefrom socket

m,to socket

Write out lineto socket

2: Application Layer 104

}}

} End of while loop,loop back and wait foranother client connection

Page 27: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

27

Chapter 2: Application layer

2.1 Principles of network applications

2.6 P2P file sharing2 7 Socket programming network applications

2.2 Web and HTTP2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP2.5 DNS

2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server

2: Application Layer 105

Socket programming with UDP

UDP: no “connection” between client and serverno handshakingsender explicitly attaches IP address and port of destination to each packetserver must extract IP address, port of sender from received packet

application viewpoint

UDP provides unreliable transferof groups of bytes (“datagrams”)

between client and server

2: Application Layer 106

p

UDP: transmitted data may be received out of order, or lost

Client/server socket interaction: UDPServer (running on hostid)

create socket

Client

create socket, create socket,clientSocket = DatagramSocket()

Create, address (hostid, port=x,send datagram request using clientSocket

create socket,port=x, forincoming request:serverSocket = DatagramSocket()

read request fromserverSocket

write reply to

2: Application Layer 107

closeclientSocket

read reply fromclientSocket

write reply toserverSocketspecifying clienthost address,port number

Example: Java client (UDP)

mU

ser

keyboard monitor

input

send

Pack

et

ecei

vePa

cket

inFr

om

Process

UDPpacket

stream

UDPpacket

Output: sends packet (recallthat TCP sent “byte stream”)

Input: receives packet (recall thatTCP received “byte stream”)

Clientprocess

2: Application Layer 108

to network from network

re

clientSocketUDP

socket

y )

client UDP socket

Page 28: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

28

Example: Java client (UDP)

import java.io.*; import java.net.*;

class UDPClient { public static void main(String args[]) throws Exception {

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();

Createinput stream

Create client socket

Translate

2: Application Layer 109

InetAddress IPAddress = InetAddress.getByName("hostname");

byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();

sendData = sentence.getBytes();

Translatehostname to IP

address using DNS

Example: Java client (UDP), cont.

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

Create datagram with data-to-send,

length, IP addr, port g ( g )

clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

String modifiedSentence = St i ( i P k t tD t ())

g , , p

Send datagramto server

Read datagramfrom server

2: Application Layer 110

new String(receivePacket.getData());

System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); }

}

Example: Java server (UDP)

import java.io.*; import java.net.*;

class UDPServer { public static void main(String args[]) throws Exception

{

DatagramSocket serverSocket = new DatagramSocket(9876);

byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024];

hil ( )

Createdatagram socket

at port 9876

2: Application Layer 111

while(true) {

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

Create space forreceived datagram

Receivedatagram

Example: Java server (UDP), contString sentence = new String(receivePacket.getData());

InetAddress IPAddress = receivePacket.getAddress(); Get IP addr

port #, ofint port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,

port);

p , fsender

Create datagramto send to client

2: Application Layer 112

port);

serverSocket.send(sendPacket); }

}

}

Write out datagramto socket

End of while loop,loop back and wait foranother datagram

Page 29: Chapter 2 Chapter 2: Application layer Application Layer 2.1 …artoo/CN2009/slides/Chapter... · 2009-03-11 · 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach,

29

Chapter 2: Summary

application architecturesclient server

our study of network apps now complete!specific protocols:

HTTPclient-serverP2Phybrid

application service requirements:

reliability, bandwidth, delay

HTTPFTPSMTP, POP, IMAPDNSP2P: BitTorrent, Skype

socket programming

2: Application Layer 113

delayInternet transport service model

connection-oriented, reliable: TCPunreliable, datagrams: UDP

Chapter 2: Summary

i l / l

Most importantly: learned about protocols

h typical request/reply message exchange:

client requests info or serviceserver responds with data, status code

message formats:

Important themes: control vs. data msgs

in-band, out-of-bandcentralized vs. decentralized stateless vs stateful

2: Application Layer 114

message formats:headers: fields giving info about datadata: info being communicated

stateless vs. statefulreliable vs. unreliable msg transfer “complexity at network edge”


Recommended