Computer Networking Application Layer Overview

119
2: Application Layer 1 Chapter 2 Application Layer Class text: Computer Networking: A Top Down Approach, 5 th edition. Jim Kurose, Keith Ross Addison-Wesley, 2010. EEE 459/591 Communication Networks Sp. 2013 Prof. Martin Reisslein All material copyright 1996-2009 J.F Kurose and K.W. Ross, All Rights Reserved

description

Networking Application Layer Overview Chapter 2 Presentation to accompany Computer Networking: A Top Down Approach, 5th ed. (Kurose, Ross) (2010)

Transcript of Computer Networking Application Layer Overview

3rd Edition: Chapter 2

2: Application Layer1Chapter 2Application LayerClass text:Computer Networking: A Top Down Approach, 5th edition. Jim Kurose, Keith RossAddison-Wesley, 2010.

EEE 459/591Communication NetworksSp. 2013Prof. Martin Reisslein

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

2: Application Layer2

2: Application Layer3Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer4Chapter 2: Application LayerOur goals: conceptual, implementation aspects of network application protocolstransport-layer service modelsclient-server paradigmpeer-to-peer paradigmlearn about protocols by examining popular application-level protocolsHTTPFTPSMTP / POP3 / IMAPDNSprogramming network applicationssocket API2: Application Layer5Some network appse-mailwebinstant messagingremote loginP2P file sharingmulti-user network gamesstreaming stored video clips

social networksvoice over IPreal-time video conferencinggrid computing

2: Application Layer6

Creating a network appwrite programs thatrun on (different) end systemscommunicate over networke.g., web server software communicates with browser softwareNo need to write software for network-core devicesNetwork-core devices do not run user applications applications on end systems allows for rapid app development, propagationapplicationtransportnetworkdata linkphysicalapplicationtransportnetworkdata linkphysicalapplicationtransportnetworkdata linkphysical2: Application Layer7Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer8Application architecturesClient-serverIncluding data centers / cloud computingPeer-to-peer (P2P)Hybrid of client-server and P2P2: Application Layer9Client-server architectureserver: always-on hostpermanent IP addressserver farms for scalingclients:communicate with servermay be intermittently connectedmay have dynamic IP addressesdo not communicate directly with each other

client/serverGoogle Data CentersEstimated cost of data center: $600MGoogle spent $2.4B in 2007 on new data centersEach data center uses 50-100 megawatts of power

2: Application Layer11Pure P2P architectureno always-on serverarbitrary end systems directly communicatepeers are intermittently connected and change IP addresses

Highly scalable but difficult to manage

peer-peer2: Application Layer12Hybrid of client-server and P2PSkypevoice-over-IP P2P applicationcentralized server: finding address of remote party: client-client connection: direct (not through server) Instant messagingchatting between two users is P2Pcentralized service: client presence detection/locationuser registers its IP address with central server when it comes onlineuser contacts central server to find IP addresses of buddies

2: Application Layer13Processes communicatingProcess: 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 messagesClient process: process that initiates communicationServer process: process that waits to be contacted

Note: applications with P2P architectures have client processes & server processes2: Application Layer14Socketsprocess sends/receives messages to/from its socketsocket analogous to doorsending process shoves message out doorsending process relies on transport infrastructure on other side of door which brings message to socket at receiving process

processTCP withbuffers,variablessockethost orserver

processTCP withbuffers,variablessockethost orserverInternetcontrolledby OS

controlled byapp developerAPI: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later) 2: Application Layer15Addressing processesto receive messages, process must have identifierhost device has unique 32-bit IP addressExercise: use ipconfig from command prompt to get your IP address (Windows)

Q: does IP address of host on which process runs suffice for identifying the process?A: No, many processes can be running on sameIdentifier includes both IP address and port numbers associated with process on host.Example port numbers:HTTP server: 80Mail server: 252: Application Layer16App-layer protocol definesTypes of messages exchanged, e.g., request, response Message syntax:what fields in messages & how fields are delineatedMessage semantics meaning of information in fieldsRules for when and how processes send & respond to messagesPublic-domain protocols:defined in RFCsallows for interoperabilitye.g., HTTP, SMTP, BitTorrentProprietary protocols:e.g., Skype, ppstream2: Application Layer17What transport service does an app need?Data losssome apps (e.g., audio) can tolerate some lossother apps (e.g., file transfer, telnet) require 100% reliable data transfer Timingsome apps (e.g., Internet telephony, interactive games) require low delay to be effectiveThroughputsome apps (e.g., multimedia) require minimum amount of throughput to be effectiveother apps (elastic apps) make use of whatever throughput they get SecurityEncryption, data integrity, 2: Application Layer18Transport service requirements of common appsApplication

file transfere-mailWeb documentsreal-time audio/video

stored audio/videointeractive gamesinstant messagingData loss

no lossno lossno lossloss-tolerant

loss-tolerantloss-tolerantno lossThroughput

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

nononoyes, 100s msec

yes, few secsyes, 100s msecyes and no2: Application Layer19Internet transport protocols servicesTCP service:connection-oriented: setup required between client and server processesreliable transport between sending and receiving processflow control: sender wont overwhelm receiver congestion control: throttle sender when network overloadeddoes not provide: timing, minimum throughput guarantees, securityUDP service:unreliable data transfer between sending and receiving processdoes not provide: connection setup, reliability, flow control, congestion control, timing, throughput guarantee, or security

Q: why bother? Why is there a UDP?2: Application Layer20Internet apps: application, transport protocolsApplication

e-mailremote terminal accessWeb file transferstreaming multimedia

Internet telephony

Applicationlayer protocol

SMTP [RFC 2821]Telnet [RFC 854]HTTP [RFC 2616]FTP [RFC 959]HTTP (eg Youtube), RTP [RFC 1889]SIP, RTP, proprietary(e.g., Skype)Underlyingtransport protocol

TCPTCPTCPTCPTCP or UDP

typically UDP2: Application Layer21Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer22Web and HTTPFirst some jargonWeb 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 URLExample URL:

www.someschool.edu/someDept/pic.gifhost namepath name2: Application Layer23HTTP overviewHTTP: hypertext transfer protocolWebs application layer protocolclient/server modelclient: browser that requests, receives, displays Web objectsserver: Web server sends objects in response to requests

PC runningExplorer

Server runningApache WebserverMac runningNavigatorHTTP requestHTTP requestHTTP responseHTTP response2: Application Layer24HTTP overview (continued)Uses TCP:client initiates TCP connection (creates socket) to server, port 80server accepts TCP connection from clientHTTP messages (application-layer protocol messages) exchanged between browser (HTTP client) and Web server (HTTP server)TCP connection closedHTTP is statelessserver maintains no information about past client requestsProtocols that maintain state are complex!past history (state) must be maintainedif server/client crashes, their views of state may be inconsistent, must be reconciled

aside2: Application Layer25HTTP connectionsNonpersistent HTTPAt most one object is sent over a TCP connection.

Persistent HTTPMultiple objects can be sent over single TCP connection between client and server.

2: Application Layer26Nonpersistent HTTPSuppose user enters URL www.someSchool.edu/someDepartment/home.index1a. HTTP client initiates TCP connection to HTTP server (process) at www.someSchool.edu on port 802. HTTP client sends HTTP request message (containing URL) into TCP connection socket. Message indicates that client wants object someDepartment/home.index1b. HTTP server at host www.someSchool.edu waiting for TCP connection at port 80. accepts connection, notifying client3. HTTP server receives request message, forms response message containing requested object, and sends message into its sockettime(contains text, references to 10 jpeg images)2: Application Layer27Nonpersistent HTTP (cont.)5. HTTP client receives response message containing html file, displays html. Parsing html file, finds 10 referenced jpeg objects6. Steps 1-5 repeated for each of 10 jpeg objects4. HTTP server closes TCP connection. time2: Application Layer28Non-Persistent HTTP: Response timeDefinition of RTT: time for a small packet to travel from client to server and back.Response time:one RTT to initiate TCP connectionone RTT for HTTP request and first few bytes of HTTP response to returnfile transmission timetotal = 2RTT+transmit time

time to transmit fileinitiate TCPconnectionRTTrequestfileRTTfilereceivedtimetime2: Application Layer29Persistent HTTPNonpersistent HTTP issues:requires 2 RTTs per objectOS overhead for each TCP connectionbrowsers often open parallel TCP connections to fetch referenced objects

Persistent HTTPserver leaves connection open after sending responsesubsequent HTTP messages between same client/server sent over open connectionclient sends requests as soon as it encounters a referenced objectas little as one RTT for all the referenced objects2: Application Layer30HTTP request messagetwo types of HTTP messages: request, responseHTTP request message:ASCII (human-readable format)GET /somedir/page.html HTTP/1.1Host: www.someschool.edu User-agent: Mozilla/4.0Connection: close Accept-language:fr

(extra carriage return, line feed) request line(GET, POST, HEAD commands)header linesCarriage return, line feed indicates end of message2: Application Layer31HTTP request message: general format

2: Application Layer32Uploading form inputPost method:Web page often includes form inputInput is uploaded to server in entity bodyURL method:Uses GET methodInput is uploaded in URL field of request line:

www.somesite.com/animalsearch?monkeys&banana2: Application Layer33Method typesHTTP/1.0GETPOSTHEADasks server to leave requested object out of responseHTTP/1.1GET, POST, HEADPUTuploads file in entity body to path specified in URL fieldDELETEdeletes file specified in the URL field2: Application Layer34HTTP response messageHTTP/1.1 200 OK 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 data data data data data ... status line(protocolstatus codestatus phrase)header linesdata, e.g., requestedHTML file2: Application Layer35HTTP response status codes200 OKrequest succeeded, requested object later in this message301 Moved Permanentlyrequested object moved, new location specified later in this message (Location:)400 Bad Requestrequest message not understood by server404 Not Foundrequested document not found on this server505 HTTP Version Not SupportedIn first line in server->client response message.A few sample codes:2: Application Layer36Trying out HTTP (client side) for yourself1. Telnet to your favorite Web server:

Opens TCP connection to port 80(default HTTP server port) at cis.poly.edu.Anything typed in sent to port 80 at cis.poly.edutelnet cis.poly.edu 802. Type in a GET HTTP request:

GET /~ross/ HTTP/1.1Host: cis.poly.eduBy typing this in (hit carriagereturn twice), you sendthis minimal (but complete) GET request to HTTP server3. Look at response message sent by HTTP server!2: Application Layer37User-server state: cookiesMany major Web sites use cookiesFour components:1) cookie header line of HTTP response message2) cookie header line in HTTP request message3) cookie file kept on users host, managed by users browser4) back-end database at Web siteExample:Susan always access Internet always from PCvisits specific e-commerce site for first timewhen initial HTTP requests arrives at site, site creates: unique IDentry in backend database for ID2: Application Layer38Cookies: keeping state (cont.)clientserverusual http response msgusual http response msgcookie fileone week later:usual http request msgcookie: 1678cookie-specificactionaccessebay 8734usual http request msgAmazon servercreates ID1678 for usercreate entryusual http response Set-cookie: 1678 ebay 8734amazon 1678usual http request msgcookie: 1678cookie-spectificactionaccessebay 8734amazon 1678backenddatabase2: Application Layer39Cookies (continued)What cookies can bring:authorizationshopping cartsrecommendationsuser session state (Web e-mail)Cookies and privacy:cookies permit sites to learn a lot about youyou may supply name and e-mail to sitesasideHow to keep state:protocol endpoints: maintain state at sender/receiver over multiple transactionscookies: http messages carry state2: Application Layer40Web caches (proxy server)user sets browser: Web accesses via cachebrowser sends all HTTP requests to cacheobject in cache: cache returns object else cache requests object from origin server, then returns object to clientGoal: satisfy client request without involving origin server

client

ProxyserverclientHTTP requestHTTP responseHTTP requestHTTP requestorigin serverorigin server

HTTP responseHTTP response

2: Application Layer41More about Web cachingcache acts as both client and servertypically cache is installed by ISP (university, company, residential ISP)Why Web caching?reduce response time for client requestreduce traffic on an institutions access link.Internet dense with caches: enables poor content providers to effectively deliver content (but so does P2P file sharing)2: Application Layer42Caching example Assumptionsaverage object size = 1,000,000 bitsavg. request rate from institutions browsers to origin servers = 15/secdelay from institutional router to any origin server and back to router = 2 secConsequencesutilization on LAN = 15%utilization on access link = 100%total delay = Internet delay + access delay + LAN delay = 2 sec + minutes + milliseconds

originserverspublic Internet

institutionalnetwork100 Mbps LAN15 Mbps access linkinstitutionalcache2: Application Layer43Caching example (cont)possible solutionincrease bandwidth of access link to, say, 100 Mbpsconsequenceutilization on LAN = 15%utilization on access link = 15%Total delay = Internet delay + access delay + LAN delay = 2 sec + msecs + msecsoften a costly upgrade

originserverspublic Internet

institutionalnetwork100 Mbps LAN100 Mbps access linkinstitutionalcache2: Application Layer44Caching example (cont)possible solution: install cachesuppose hit rate is 0.4consequence40% requests will be satisfied almost immediately60% requests satisfied by origin serverutilization of access link reduced to 60%, resulting in negligible delays (say 10 msec)total avg delay = Internet delay + access delay + LAN delay = .6*(2.01) secs + .4*milliseconds < 1.4 secs

originserverspublic Internet

institutionalnetwork100 Mbps LAN15 Mbps access linkinstitutionalcache2: Application Layer45Conditional GETGoal: dont send object if cache has up-to-date cached versioncache: specify date of cached copy in HTTP requestIf-modified-since: server: response contains no object if cached copy is up-to-date: HTTP/1.0 304 Not ModifiedcacheserverHTTP request msgIf-modified-since: HTTP responseHTTP/1.0 304 Not Modifiedobject not modifiedHTTP request msgIf-modified-since: HTTP responseHTTP/1.0 200 OK

object modified2: Application Layer46Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer47FTP: the file transfer protocoltransfer file to/from remote hostclient/server modelclient: side that initiates transfer (either to/from remote)server: remote hostftp: RFC 959ftp server: port 21

file transferFTPserverFTPuserinterfaceFTPclientlocal filesystemremote filesystem

user at host2: Application Layer48FTP: separate control, data connectionsFTP client contacts FTP server at port 21, TCP is transport protocolclient authorized over control connectionclient browses remote directory by sending commands over control connection.when server receives file transfer command, server opens 2nd TCP connection (for file) to clientafter transferring one file, server closes data connection.

FTPclientFTPserverTCP control connectionport 21TCP data connectionport 20server opens another TCP data connection to transfer another file.control connection: out of bandFTP server maintains state: current directory, earlier authentication

2: Application Layer49FTP commands, responsesSample commands:sent as ASCII text over control channelUSER usernamePASS passwordLIST return list of file in current directoryRETR filename retrieves (gets) fileSTOR filename stores (puts) file onto remote hostSample return codesstatus code and phrase (as in HTTP)331 Username OK, password required125 data connection already open; transfer starting425 Cant open data connection452 Error writing file2: Application Layer50Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer51Electronic MailThree major components: user agents mail servers simple mail transfer protocol: SMTPUser Agenta.k.a. mail readercomposing, editing, reading mail messagese.g., Eudora, Outlook, elm, Mozilla Thunderbirdoutgoing, incoming messages stored on serveruser mailboxoutgoing message queuemailserver

useragent

useragent

useragentmailserver

useragent

useragentmailserver

useragentSMTPSMTPSMTP2: Application Layer52Electronic Mail: mail serversMail Servers mailbox contains incoming messages for usermessage queue of outgoing (to be sent) mail messagesSMTP protocol between mail servers to send email messagesclient: sending mail serverserver: receiving mail servermailserver

useragent

useragent

useragentmailserver

useragent

useragentmailserver

useragentSMTPSMTPSMTP2: Application Layer53Electronic 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 transferhandshaking (greeting)transfer of messagesclosurecommand/response interactioncommands: ASCII textresponse: status code and phrasemessages must be in 7-bit ASCII

2: Application Layer54Scenario: Alice sends message to Bob1) Alice uses UA to compose message and to [email protected]) Alices UA sends message to her mail server; message placed in message queue3) Client side of SMTP opens TCP connection with Bobs mail server4) SMTP client sends Alices message over the TCP connection5) Bobs mail server places the message in Bobs mailbox6) Bob invokes his user agent to read message

useragentmailserver

mailserver

useragent1234562: Application Layer55Sample SMTP interaction S: 220 hamburger.edu C: HELO crepes.fr S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: S: 250 [email protected]... Sender ok C: RCPT TO: 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? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger.edu closing connection2: Application Layer56Try SMTP interaction for yourself:telnet servername 25see 220 reply from serverenter HELO, MAIL FROM, RCPT TO, DATA, QUIT commands above lets you send email without using email client (reader)2: Application Layer57SMTP: final wordsSMTP uses persistent connectionsSMTP requires message (header & body) to be in 7-bit ASCIISMTP server uses CRLF.CRLF to determine end of messageComparison with HTTP:HTTP: pullSMTP: pushboth have ASCII command/response interaction, status codesHTTP: each object encapsulated in its own response msgSMTP: multiple objects sent in multipart msg2: Application Layer58Mail message formatSMTP: protocol for exchanging email msgsRFC 822: standard for text message format:header lines, e.g.,To:From:Subject:different from SMTP commands!bodythe message, ASCII characters onlyheaderbodyblankline2: Application Layer59Mail access protocolsSMTP: delivery/storage to receivers serverMail access protocol: retrieval from serverPOP: Post Office Protocol [RFC 1939]authorization (agent server) and download IMAP: Internet Mail Access Protocol [RFC 1730]more features (more complex)manipulation of stored msgs on serverHTTP: gmail, Hotmail, Yahoo! Mail, etc.

useragentsenders mail server

useragentSMTPSMTPaccessprotocolreceivers mail server

2: Application Layer60POP3 protocolauthorization phaseclient commands: user: declare usernamepass: passwordserver responses+OK-ERRtransaction phase, client:list: list message numbersretr: retrieve message by numberdele: deletequit C: list S: 1 498 S: 2 912 S: . C: retr 1 S: S: . C: dele 1 C: retr 2 S: S: . C: dele 2 C: quit S: +OK POP3 server signing offS: +OK POP3 server ready C: user bob S: +OK C: pass hungry S: +OK user successfully logged on2: Application Layer61POP3 (more) and IMAPMore about POP3Previous example uses download and delete mode.Bob cannot re-read e-mail if he changes clientDownload-and-keep: copies of messages on different clientsPOP3 is stateless across sessionsIMAPKeep all messages in one place: the serverAllows user to organize messages in foldersIMAP keeps user state across sessions:names of folders and mappings between message IDs and folder name2: Application Layer62Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer63DNS: Domain Name SystemPeople: many identifiers:SSN, name, passport #Internet hosts, routers:IP address (32 bit) - used for addressing datagramsname, e.g., ww.yahoo.com - used by humansQ: map between IP addresses and name ?Domain Name System:distributed database implemented in hierarchy of many name serversapplication-layer protocol host, routers, name servers to communicate to resolve names (address/name translation)note: core Internet function, implemented as application-layer protocolcomplexity at networks edge2: Application Layer64DNS Why not centralize DNS?single point of failuretraffic volumedistant centralized databasemaintenance

doesnt scale!DNS serviceshostname to IP address translationhost aliasingCanonical, alias namesmail server aliasingload distributionreplicated Web servers: set of IP addresses for one canonical name

2: Application Layer65Root DNS Serverscom DNS serversorg DNS serversedu DNS serverspoly.eduDNS serversumass.eduDNS serversyahoo.comDNS serversamazon.comDNS serverspbs.orgDNS serversDistributed, Hierarchical DatabaseClient wants IP for www.amazon.com; 1st approx:client queries a root server to find com DNS serverclient queries com DNS server to get amazon.com DNS serverclient queries amazon.com DNS server to get IP address for www.amazon.com2: Application Layer66DNS: Root name serverscontacted by local name server that can not resolve nameroot name server:contacts authoritative name server if name mapping not knowngets mappingreturns mapping to local name server 13 root name servers worldwide

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

e NASA Mt View, CAf Internet Software C. Palo Alto, CA (and 36 other locations)

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 Layer67TLD and Authoritative ServersTop-level domain (TLD) servers: 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 TLDAuthoritative DNS servers: organizations DNS servers, providing authoritative hostname to IP mappings for organizations servers (e.g., Web, mail).can be maintained by organization or service provider

2: Application Layer68Local Name Serverdoes not strictly belong to hierarchyeach ISP (residential ISP, company, university) has one.also called default name serverwhen host makes DNS query, query is sent to its local DNS serveracts as proxy, forwards query into hierarchy2: Application Layer69

requesting hostcis.poly.edugaia.cs.umass.edu

root DNS serverlocal DNS serverdns.poly.edu123456authoritative DNS serverdns.cs.umass.edu78TLD DNS serverDNS name resolution exampleHost at cis.poly.edu wants IP address for gaia.cs.umass.eduiterated query:contacted server replies with name of server to contactI dont know this name, but ask this server2: Application Layer70

requesting hostcis.poly.edugaia.cs.umass.edu

root DNS serverlocal DNS serverdns.poly.edu12456authoritative DNS serverdns.cs.umass.edu78TLD DNS server3recursive query:puts burden of name resolution on contacted name serverheavy load?DNS name resolution example2: Application Layer71DNS: caching and updating recordsonce (any) name server learns mapping, it caches mappingcache entries timeout (disappear) after some timeTLD servers typically cached in local name serversThus root name servers not often visitedupdate/notify mechanisms under design by IETFRFC 2136http://www.ietf.org/html.charters/dnsind-charter.html2: Application Layer72DNS recordsDNS: distributed db storing resource records (RR)Type=NSname is domain (e.g. foo.com)value is hostname of authoritative name server for this domain

RR format: (name, value, type, ttl)Type=Aname is hostnamevalue is IP address

Type=CNAMEname is alias name for some canonical (the real) name www.ibm.com is really servereast.backup2.ibm.comvalue is canonical name

Type=MXvalue is name of mailserver associated with name

2: Application Layer73DNS protocol, messagesDNS protocol : query and reply messages, both with same message formatmsg headeridentification: 16 bit # for query, reply to query uses same #flags:query or replyrecursion desired recursion availablereply is authoritative

2: Application Layer74DNS protocol, messages

Name, type fields for a queryRRs in responseto queryrecords forauthoritative serversadditional helpfulinfo that may be used2: Application Layer75Inserting records into DNSexample: new startup Network Utopiaregister name networkuptopia.com at DNS registrar (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)

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?

2: Application Layer76Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer77Pure P2P architectureno always-on serverarbitrary end systems directly communicatepeers are intermittently connected and change IP addresses

Three topics:File distributionSearching for informationCase Study: Skype

peer-peer2: Application Layer78File Distribution: Server-Client vs P2PQuestion : How much time to distribute file from one server to N peers?us

u2d1

d2u1

uNdNServerNetwork (with abundant bandwidth)File, size Fus: server upload bandwidthui: peer i upload bandwidthdi: peer i download bandwidth2: Application Layer79File distribution time: server-clientus

u2d1

d2u1

uNdNServerNetwork (with abundant bandwidth)Fserver sequentially sends N copies:NF/us time client i takes F/di time to downloadincreases linearly in N(for large N)= dcs = max { NF/us, F/min(di) }iTime to distribute F to N clients using client/server approach 2: Application Layer80File distribution time: P2Pus

u2d1

d2u1

uNdNServerNetwork (with abundant bandwidth)Fserver must send one copy: F/us time client i takes F/di time to downloadNF bits must be downloaded (aggregate)fastest possible upload rate: us + SuidP2P = max { F/us, F/min(di) , NF/(us + Sui) }i2: Application Layer81

Server-client vs. P2P: exampleClient upload rate = u, F/u = 1 hour, us = 10u, dmin us2: Application Layer82File distribution: BitTorrent tracker: tracks peers participating in torrenttorrent: group of peers exchanging chunks of a file

obtain listof peers trading chunks

peerP2P file distribution2: Application Layer83BitTorrent (1)file 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 peers. peers may come and goonce peer has entire file, it may (selfishly) leave or (altruistically) remain

2: Application Layer84BitTorrent (2)Pulling Chunksat any given time, different peers have different subsets of file chunksperiodically, a peer (Alice) asks each neighbor for list of chunks that they have.Alice sends requests for her missing chunksrarest firstSending Chunks: tit-for-tatAlice sends chunks to four neighbors currently sending her chunks at the highest rate re-evaluate top 4 every 10 secsevery 30 secs: randomly select another peer, starts sending chunksnewly chosen peer may join top 4optimistically unchoke

2: Application Layer85BitTorrent: Tit-for-tat

(1) Alice optimistically unchokes Bob(2) Alice becomes one of Bobs top-four providers; Bob reciprocates(3) Bob becomes one of Alices top-four providersWith higher upload rate, can find better trading partners & get file faster!Distributed Hash Table (DHT)DHT = distributed P2P databaseDatabase has (key, value) pairs; key: ss number; value: human namekey: content type; value: IP addressPeers query DB with keyDB returns values that match the keyPeers can also insert (key, value) peersDHT IdentifiersAssign 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 tableHow 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 in lecture: closest is the immediate successor of the key.Ex: n=4; peers: 1,3,4,5,8,10,12,14; key = 13, then successor peer = 14key = 15, then successor peer = 113458101215Circular DHT (1)Each peer only aware of immediate successor and predecessor.Overlay networkCircle DHT (2)

00010011010001011000101011001111Whos resp for key 1110 ?I amO(N) messageson avg to resolvequery, when thereare N peers111011101110111011101110Define closestas closestsuccessorCircular DHT with ShortcutsEach 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 query13458101215Whos resp for key 1110? Peer ChurnPeer 5 abruptly leavesPeer 4 detects; makes 8 its immediate successor; asks 8 who its immediate successor is; makes 8s immediate successor its second successor.What if peer 13 wants to join?13458101215To handle peer churn, require each peer to know the IP address of its two successors. Each peer periodically pings its two successors to see if they are still alive.

2: Application Layer93P2P Case study: Skypeinherently P2P: pairs of users communicate.proprietary application-layer protocol (inferred via reverse engineering) hierarchical overlay with SNsIndex maps usernames to IP addresses; distributed over SNs

Skype clients (SC)Supernode (SN)Skype login server2: Application Layer94Peers as relaysProblem when both Alice and Bob are behind NATs. NAT prevents an outside peer from initiating a call to insider peerSolution:Using Alices and Bobs SNs, Relay is chosenEach peer initiates session with relay. Peers can now communicate through NATs via relay

2: Application Layer95Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer96Socket programmingSocket APIintroduced in BSD4.1 UNIX, 1981explicitly created, used, released by apps client/server paradigm two types of transport service via socket API: UDPTCPA application-created, OS-controlled interface (a door) into whichapplication process can both send and receive messages to/from another application process

socketGoal: learn how to build client/server application that communicate using socketsSocket programming basicsServer must be running before client can send anything to it.Server must have a socket (door) through which it receives and sends segmentsSimilarly client needs a socketSocket is locally identified with a port numberAnalogous to the apt # in a buildingClient needs to know server IP address and socket port number.

2: Application Layer972: Application Layer98Socket programming with UDPUDP: no connection between client and serverno handshakingsender explicitly attaches IP address and port of destination to each segmentOS attaches IP address and port of sending socket to each segmentServer can extract IP address, port of sender from received segmentapplication viewpointUDP provides unreliable transfer of groups of bytes (datagrams) between client and server

Note: the official terminology for a UDP packet is datagram. In this class, we instead use UDP segment.Running exampleClient: User types line of textClient program sends line to serverServer:Server receives line of textCapitalizes all the lettersSends modified line to clientClient:Receives line of textDisplays2: Application Layer992: Application Layer100Client/server socket interaction: UDPServer (running on hostid)closeclientSocketread datagram fromclientSocketcreate socket,

clientSocket = DatagramSocket()ClientCreate datagram with server IP andport=x; send datagram via clientSocketcreate socket,port= x.serverSocket = DatagramSocket()read datagram fromserverSocketwrite reply toserverSocketspecifying client address,port number2: Application Layer101Example: Java client (UDP)

Output: sends packet (recallthat TCP sent byte stream)Input: receives packet (recall thatTCP received byte stream)Clientprocessclient UDP socket2: Application Layer102Example: 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(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Createinput streamCreate client socketTranslate hostname to IP address using DNS2: Application Layer103Example: Java client (UDP), cont. DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } Create datagram with data-to-send,length, IP addr, port

Send datagramto serverRead datagramfrom server2: Application Layer104Example: 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]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); Createdatagram socketat port 9876Create space forreceived datagramReceivedatagram2: Application Layer105Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } Get IP addrport #, ofsenderWrite out datagramto socketEnd of while loop,loop back and wait foranother datagramCreate datagramto send to clientUDP observations & questionsBoth client server use DatagramSocket Dest IP and port are explicitly attached to segment.What would happen if change both clientSocket and serverSocket to mySocket?Can the client send a segment to server without knowing the servers IP address and/or port number?Can multiple clients use the server?

2: Application Layer1062: Application Layer107Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS

2.6 P2P applications2.7 Socket programming with UDP2.8 Socket programming with TCP2: Application Layer108Socket-programming using TCPTCP service: reliable transfer of bytes from one process to another

processTCP withbuffers,variablessocketcontrolled byapplicationdevelopercontrolled byoperatingsystemhost orserver

processTCP withbuffers,variablessocketcontrolled byapplicationdevelopercontrolled byoperatingsystemhost orserverinternet2: Application Layer109Socket programming with TCPClient must contact serverserver process must first be runningserver must have created socket (door) that welcomes clients contactClient contacts server by:creating client-local TCP socketspecifying IP address, port number of server processWhen client creates socket: client TCP establishes connection to server TCP

When contacted by client, server TCP creates new socket for server process to communicate with clientallows server to talk with multiple clientssource port numbers used to distinguish clients (more in Chap 3)TCP provides reliable, in-order transfer of bytes (pipe) between client and serverapplication viewpoint2: Application Layer110Client/server socket interaction: TCPwait for incomingconnection requestconnectionSocket =welcomeSocket.accept()create socket,port=x, forincoming request:welcomeSocket = ServerSocket()create socket,connect to hostid, port=xclientSocket = Socket()closeconnectionSocketread reply fromclientSocketcloseclientSocketServer (running on hostid)Clientsend request usingclientSocketread request fromconnectionSocketwrite reply toconnectionSocketTCP connection setup2: Application Layer111

Clientprocessclient TCP socketStream jargonA stream is a sequence of characters that flow into 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 source, e.g., monitor or socket.2: Application Layer112Socket programming with TCPExample client-server app:1) client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream)2) server reads line from socket3) server converts line to uppercase, sends back to client4) client reads, prints modified line from socket (inFromServer stream)2: Application Layer113Example: Java client (TCP)import java.io.*; import java.net.*; class TCPClient {

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

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

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

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

Createinput streamCreate client socket, connect to serverCreateoutput streamattached to socket2: Application Layer114Example: Java client (TCP), cont. BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();

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

modifiedSentence = inFromServer.readLine();

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

clientSocket.close(); } } Createinput streamattached to socketSend lineto serverRead linefrom server2: Application Layer115Example: 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) { Socket connectionSocket = welcomeSocket.accept();

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

Createwelcoming socketat port 6789Wait, on welcomingsocket for contactby clientCreate inputstream, attached to socket2: Application Layer116Example: Java server (TCP), cont DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

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

outToClient.writeBytes(capitalizedSentence); } } } Read in linefrom socketCreate outputstream, attached to socketWrite out lineto socketEnd of while loop,loop back and wait foranother client connectionTCP observations & questionsServer has two types of sockets: ServerSocket and Socket When client knocks on serverSockets door, server creates connectionSocket and completes TCP conx.Dest IP and port are not explicitly attached to segment.Can multiple clients use the server?

2: Application Layer1172: Application Layer118Chapter 2: Summaryapplication architecturesclient-serverP2Phybridapplication service requirements: reliability, bandwidth, delayInternet transport service modelconnection-oriented, reliable: TCPunreliable, datagrams: UDPour study of network apps now complete!specific protocols:HTTPFTPSMTP, POP, IMAPDNSP2P: BitTorrent, Skypesocket programming2: Application Layer119Chapter 2: Summarytypical request/reply message exchange:client requests info or serviceserver responds with data, status codemessage formats:headers: fields giving info about datadata: info being communicatedMost importantly: learned about protocolsImportant themes: control vs. data msgsin-band, out-of-bandcentralized vs. decentralized stateless vs. statefulreliable vs. unreliable msg transfer complexity at network edgeChart10.10.10.16666666670.20.23076923080.30.28571428570.40.33333333330.50.3750.60.41176470590.70.44444444440.80.47368421050.90.510.52380952381.10.54545454551.20.56521739131.30.58333333331.40.61.50.61538461541.60.62962962961.70.64285714291.80.65517241381.90.666666666720.67741935482.10.68752.20.6969696972.30.70588235292.40.71428571432.50.72222222222.60.72972972972.70.73684210532.80.74358974362.90.7530.7560975613.10.76190476193.2

P2PClient-ServerNMinimum Distribution Time

Sheet1LP2PClient-Serverratiofactor10.10.111020.16666666670.230.23076923080.340.28571428570.450.33333333330.560.3750.670.41176470590.780.44444444440.890.47368421050.9100.51110.52380952381.1120.54545454551.2130.56521739131.3140.58333333331.4150.61.5160.61538461541.6170.62962962961.7180.64285714291.8190.65517241381.9200.66666666672210.67741935482.1220.68752.2230.6969696972.3240.70588235292.4250.71428571432.5260.72222222222.6270.72972972972.7280.73684210532.8290.74358974362.9300.753310.7560975613.1320.76190476193.2330.76744186053.3340.77272727273.4350.77777777783.5360.78260869573.6370.78723404263.7380.79166666673.8390.79591836733.9400.84410.80392156864.1420.80769230774.2430.81132075474.3440.81481481484.4450.81818181824.5460.82142857144.6470.82456140354.7480.82758620694.8490.83050847464.9

Sheet10000000000000000000000000000000000000000000000000000000000000000

P2PClient-ServerNMinimum Distribution Time

Sheet2

Sheet3