2: Application Layer1Chapter 2Application LayerComputer Networking: A Top Down Approach, 4thedition. Jim Kurose, Keith RossAddison-Wesley, July 2007. 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 lotof work on our part. In return for use, we only ask the 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/KWRAll material copyright 1996-2007J.F Kurose and K.W. Ross, All Rights Reserved2: Application Layer2Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS2.6 P2P Applications2.7 Socket programming with TCP2.8 Socket programming with UDP2: Application Layer3Chapter 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 Layer4Some network appse-mailwebinstant messagingremote loginP2P file sharingmulti-user network gamesstreaming stored video clipsvoice over IPreal-time video conferencinggrid computing2: Application Layer5Creating a network appwrite programs thatrun on (different) end systemscommunicate over networke.g., web server software communicates with browser softwarelittle software written for devices in network corenetwork core devices do not run user applications applications on end systems allows for rapid app development, propagationapplicationtransportnetworkdata linkphysicalapplicationtransportnetworkdata linkphysicalapplicationtransportnetworkdata linkphysical2: Application Layer6Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server2: Application Layer7Application architecturesClient-serverPeer-to-peer (P2P)Hybrid of client-server and P2P2: Application Layer8Client-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 otherclient/server2: Application Layer9Pure P2P architecturenoalways-on serverarbitrary end systems directly communicatepeers are intermittently connected and change IP addressesexample: GnutellaHighly scalable but difficult to managepeer-peer2: Application Layer10Hybrid 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/location•user registers its IP address with central server when it comes online•user contacts central server to find IP addresses of buddies2: Application Layer11Processes 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 contactedNote: applications with P2P architectures have client processes & server processes2: Application Layer12Socketsprocess 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 processprocessTCP withbuffers,variablessockethost orserverprocessTCP withbuffers,variablessockethost orserverInternetcontrolledby OScontrolled byapp developerAPI: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later)2: Application Layer13Addressing processesto receive messages, process must have identifierhost device has unique 32-bit IP addressQ:does IP address of host on which process runs suffice for identifying the process?2: Application Layer14Addressing processesto receive messages, process must have identifierhost device has unique 32-bit IP addressQ:does IP address of host on which process runs suffice for identifying the process?A:No, manyprocesses can be running on same hostidentifierincludes both IP addressand port numbersassociated with process on host.Example port numbers:HTTP server: 80Mail server: 25to send HTTP message to gaia.cs.umass.edu web server:IP address:128.119.245.12Port number:80more shortly…2: Application Layer15App-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, SMTPProprietary protocols:e.g., Skype2: Application Layer16What 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 transferTimingsome apps (e.g., Internet telephony, interactive games) require low delay to be “effective”Bandwidthsome apps (e.g., multimedia) require minimum amount of bandwidth to be “effective”other apps (“elastic apps”) make use of whatever bandwidth they get 2: Application Layer17Transport service requirements of common appsApplicationfile transfere-mailWeb documentsreal-time audio/videostored audio/videointeractive gamesinstant messagingData lossno lossno lossno lossloss-tolerantloss-tolerantloss-tolerantno lossBandwidthelasticelasticelasticaudio: 5kbps-1Mbpsvideo:10kbps-5Mbpssame as above few kbps upelasticTime Sensitivenononoyes, 100’s msecyes, few secsyes, 100’s msecyes and no2: Application Layer18Internet transport protocols servicesTCP service:connection-oriented:setup required between client and server processesreliable transport between sending and receiving processflow control:sender won’t overwhelm receiver congestion control:throttle sender when network overloadeddoes not provide:timing, minimum bandwidth guaranteesUDP service:unreliable data transfer between sending and receiving processdoes not provide: connection setup, reliability, flow control, congestion control, timing, or bandwidth guarantee Q:why bother? Why is there a UDP?2: Application Layer19Internet apps: application, transport protocolsApplicatione-mailremote terminal accessWeb file transferstreaming multimediaInternet telephonyApplicationlayer protocolSMTP [RFC 2821]Telnet [RFC 854]HTTP [RFC 2616]FTP [RFC 959]proprietary(e.g. RealNetworks)proprietary(e.g., Vonage,Dialpad)Underlyingtransport protocolTCPTCPTCPTCPTCP or UDPtypically UDP2: Application Layer20Chapter 2: Application layer2.1 Principles of network applications app architecturesapp requirements2.2 Web and HTTP2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2: Application Layer21Web and HTTPFirst some jargonWeb pageconsists of objectsObject can be HTML file, JPEG image, Java applet, audio file,…Web page consists of base HTML-filewhich includes several referenced objectsEach object is addressable by a URLExample URL:www.someschool.edu/someDept/pic.gifhost namepath name2: Application Layer22HTTP overviewHTTP: hypertext transfer protocolWeb’s application layer protocolclient/server modelclient:browser that requests, receives, “displays” Web objectsserver:Web server sends objects in response to requestsHTTP 1.0: RFC 1945HTTP 1.1: RFC 2068PC runningExplorerServer runningApache WebserverMac runningNavigatorHTTP requestHTTP responseHTTP response2: Application Layer23HTTP 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 “stateless”server 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 reconciledaside2: Application Layer24HTTP connectionsNonpersistent HTTPAt most one object is sent over a TCP connection.HTTP/1.0 uses nonpersistent HTTPPersistent HTTPMultiple objects can be sent over single TCP connection between client and server.HTTP/1.1 uses persistent connections in default mode2: Application Layer25Nonpersistent 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.HTTPclient sends HTTP request message(containing URL) into TCP connection socket. Message indicates that client wants object someDepartment/home.index1b.HTTPserver at host www.someSchool.edu waiting for TCP connection at port 80. “accepts” connection, notifying client3.HTTPserver receives request message, forms response messagecontaining requested object, and sends message into its sockettime(contains text, references to 10 jpeg images)2: Application Layer26Nonpersistent 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.HTTPserver closes TCP connection. time2: Application Layer27Non-Persistent HTTP: Response timeDefinition of RTT:time to send 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 timetime to transmit fileinitiate TCPconnectionRTTrequestfileRTTfilereceivedtimetime2: Application Layer28Persistent HTTPNonpersistent HTTP issues:requires 2 RTTs per objectOS overhead for eachTCP connectionbrowsers often open parallel TCP connections to fetch referenced objectsPersistent HTTPserver leaves connection open after sending responsesubsequent HTTP messages between same client/server sent over open connectionPersistent withoutpipelining:client issues new request only when previous response has been receivedone RTT for each referenced objectPersistent withpipelining:default in HTTP/1.1client sends requests as soon as it encounters a referenced objectas little as one RTT for all the referenced objects2: Application Layer29HTTP 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)headerlinesCarriage return, line feed indicates end of message2: Application Layer30HTTP request message: general format2: Application Layer31Uploading 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 Layer32Method 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 Layer33HTTP 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/htmldata data data data data ... status line(protocolstatus codestatus phrase)headerlinesdata, e.g., requestedHTML file2: Application Layer34HTTP 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 Layer35Trying 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 Layer36Let’s look at HTTP in actiontelnet exampleEthereal example2: Application Layer37User-server state: cookiesMany major Web sites use cookiesFour components:1) cookie header line of HTTP responsemessage2) cookie header line in HTTP requestmessage3) cookie file kept on user’s host, managed by user’s 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 usercreateentryusual 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 serverclientProxyserverclientHTTP requestHTTP responseHTTP requestorigin serverorigin serverHTTP response2: 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 institution’s 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 = 100,000 bitsavg. request rate from institution’s 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 + millisecondsoriginserverspublicInternetinstitutionalnetwork10 Mbps LAN1.5 Mbps access linkinstitutionalcache2: Application Layer43Caching example (cont)possible solutionincrease bandwidth of access link to, say, 10 Mbpsconsequenceutilization on LAN = 15%utilization on access link = 15%Total delay = Internet delay + access delay + LAN delay= 2 sec + msecs + msecsoften a costly upgradeoriginserverspublicInternetinstitutionalnetwork10 Mbps LAN10 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 secsoriginserverspublicInternetinstitutionalnetwork10 Mbps LAN1.5 Mbps access linkinstitutionalcache2: Application Layer45Conditional GETGoal:don’t 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 OKobject modified2: Application Layer46Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server2: 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 21file transferFTPserverFTPuserinterfaceFTPclientlocal filesystemremote filesystemuser 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 2ndTCP 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 band”FTP server maintains “state”: current directory, earlier authentication2: Application Layer49FTP commands, responsesSample commands:sent as ASCII text over control channelUSER usernamePASS passwordLISTreturn list of file in current directoryRETR filenameretrieves (gets) fileSTOR filenamestores (puts) file onto remote hostSample return codesstatus code and phrase (as in HTTP)331 Username OK, password required125 data connection already open; transfer starting425 Can’t 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 DNS2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server2: Application Layer51Electronic MailThree major components:user agents mail servers simple mail transfer protocol: SMTPUser Agenta.k.a. “mail reader”composing, editing, reading mail messagese.g., Eudora, Outlook, elm, Mozilla Thunderbirdoutgoing, incoming messages stored on serveruser mailboxoutgoing message queuemailserveruseragentuseragentuseragentmailserveruseragentuseragentmailserveruseragentSMTPSMTPSMTP2: Application Layer52Electronic Mail: mail serversMail Serversmailboxcontains incoming messages for usermessagequeueof outgoing (to be sent) mail messagesSMTP protocolbetween mail servers to send email messagesclient: sending mail server“server”: receiving mail servermailserveruseragentuseragentuseragentmailserveruseragentuseragentmailserveruseragentSMTPSMTPSMTP2: 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 ASCII2: Application Layer54Scenario: Alice sends message to Bob1) Alice uses UA to compose message and “to” bob@someschool.edu2) Alice’s UA sends message to her mail server; message placed in message queue3) Client side of SMTP opens TCP connection with Bob’s mail server4) SMTP client sends Alice’s message over the TCP connection5) Bob’s mail server places the message in Bob’s mailbox6) Bob invokes his user agent to read messageuseragentmailservermailserveruseragent1234562: Application Layer55Sample SMTP interactionS: 220 hamburger.edu C: HELO crepes.fr S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: S: 250 alice@crepes.fr... Sender ok C: RCPT TO: S: 250 bob@hamburger.edu ... Recipient ok C: DATA S: 354 Enter mail, end with "." on a line by itself C: Do you like ketchup? C: How about pickles? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger.edu closing connection2: Application Layer56Try SMTP interaction for yourself:telnet servername 25see 220 reply from serverenter HELO, MAIL FROM, RCPT TO, DATA, QUIT commandsabove 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.CRLFto 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:differentfrom SMTP commands!bodythe “message”, ASCII characters onlyheaderbodyblankline2: Application Layer59Message format: multimedia extensionsMIME: multimedia mail extension, RFC 2045, 2056additional lines in msg header declare MIME content typeFrom: alice@crepes.fr To: bob@hamburger.edu Subject: Picture of yummy crepe. MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Type: image/jpeg base64 encoded data ..... ......................... ......base64 encoded data multimedia datatype, subtype, parameter declarationmethod usedto encode dataMIME versionencoded data2: Application Layer60Mail access protocolsSMTP: delivery/storage to receiver’s 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.useragentsender’s mail serveruseragentSMTPSMTPaccessprotocolreceiver’s mail server2: Application Layer61POP3 protocolauthorization phaseclient commands: user:declare usernamepass:passwordserver responses+OK-ERRtransaction phase, client:list:list message numbersretr:retrieve message by numberdele:deletequitC: 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: +OKuser successfully logged on2: Application Layer62POP3 (more) and IMAPMore about POP3Previous example uses “download and delete” mode.Bob cannot re-read e-mail if he changes client“Download-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 Layer63Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server2: Application Layer64DNS: Domain Name SystemPeople:many identifiers:SSN, name, passport #Internet hosts, routers:IP address (32 bit) -used for addressing datagrams“name”, e.g., ww.yahoo.com -used by humansQ:map between IP addresses and name ?Domain Name System:distributed databaseimplemented in hierarchy of many name serversapplication-layer protocolhost, routers, name servers to communicate to resolvenames (address/name translation)note: core Internet function, implemented as application-layer protocolcomplexity at network’s “edge”2: Application Layer65DNS Why not centralize DNS?single point of failuretraffic volumedistant centralized databasemaintenancedoesn’t scale!DNS serviceshostname to IP address translationhost aliasingCanonical, alias namesmail server aliasingload distributionreplicated Web servers: set of IP addresses for one canonical name2: Application Layer66Root 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; 1stapprox: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 Layer67DNS: 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 server13 root name servers worldwideb USC-ISI Marina del Rey, CAl ICANN Los Angeles, CAe NASA Mt View, CAf Internet Software C. PaloAlto, 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 Layer68TLD 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:organization’s DNS servers, providing authoritative hostname to IP mappings for organization’s servers (e.g., Web, mail).can be maintained by organization or service provider2: Application Layer69Local Name Serverdoes not strictly belong to hierarchyeach ISP (residential ISP, company, university) has one.also called “default name server”when host makes DNS query, query is sent to its local DNS serveracts as proxy, forwards query into hierarchy2: Application Layer70requesting hostcis.poly.edugaia.cs.umass.eduroot 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 contact“I don’t know this name, but ask this server”2: Application Layer71requesting hostcis.poly.edugaia.cs.umass.eduroot 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 Layer72DNS: caching and updating recordsonce (any) name server learns mapping, it cachesmappingcache 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 IETFRFC 2136http://www.ietf.org/html.charters/dnsind-charter.html2: Application Layer73DNS recordsDNS:distributed db storing resource records (RR)Type=NSnameis domain (e.g. foo.com)valueis hostname of authoritative name server for this domainRR format: (name, value, type, ttl)Type=Anameis hostnamevalueis IP addressType=CNAMEnameis alias name for some “canonical” (the real) namewww.ibm.com is reallyservereast.backup2.ibm.comvalueis canonical nameType=MXvalueis name of mailserver associated with name2: Application Layer74DNS protocol, messagesDNS protocol :queryand replymessages, both with same message formatmsg headeridentification:16 bit # for query, reply to query uses same #flags:query or replyrecursion desired recursion availablereply is authoritative2: Application Layer75DNS protocol, messagesName, type fieldsfor a queryRRs in responseto queryrecords forauthoritative serversadditional “helpful”info that may be used2: Application Layer76Inserting records into DNSexample: new startup “Network Utopia”register 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 Layer77Chapter 2: Application layer2.1 Principles of network applications app architecturesapp requirements2.2 Web and HTTP2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server2: Application Layer78P2P file sharingExampleAlice runs P2P client application on her notebook computerintermittently connects to Internet; gets new IP address for each connectionasks for “Hey Jude”application displays other peers that have copy of Hey Jude.Alice chooses one of the peers, Bob.file is copied from Bob’s PC to Alice’s notebook: HTTPwhile Alice downloads, other users uploading from Alice.Alice’s peer is both a Web client and a transient Web server.All peers are servers = highly scalable!2: Application Layer79P2P: centralized directoryoriginal “Napster” design1) when peer connects, it informs central server:IP addresscontent2) Alice queries for “Hey Jude”3) Alice requests file from Bobcentralizeddirectory serverpeersAliceBob1111232: Application Layer80P2P: problems with centralized directorysingle point of failureperformance bottleneckcopyright infringement: “target” of lawsuit is obviousfile transfer is decentralized, but locating content is highly centralized2: Application Layer81Query flooding: Gnutellafully distributedno central serverpublic domain protocolmany Gnutella clients implementing protocoloverlay network: graphedge between peer X and Y if there’s a TCP connectionall active peers and edges form overlay netedge: virtual (notphysical) linkgiven peer typically connected with < 10 overlay neighbors2: Application Layer82Gnutella: protocolQueryQueryHitQueryQueryQueryHitQueryQueryQueryHitFile transfer:HTTPQuery messagesent over existing TCPconnectionspeers forwardQuery messageQueryHit sent over reversepathScalability:limited scopeflooding2: Application Layer83Gnutella: Peer joining1.joining peer Alice must find another peer in Gnutella network: use list of candidate peers2.Alice sequentially attempts TCP connections with candidate peers until connection setup with Bob3.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 with Pong message4.Alice receives many Pong messages, and can then setup additional TCP connectionsPeer leaving: see homework problem!2: Application Layer84Hierarchical Overlaybetween centralized index, query flooding approacheseach peer is either a group leaderor assigned to a group leader.TCP connection between peer and its group leader.TCP connections between some pairs of group leaders.group leader tracks content in its childrenordinary peergroup-leader peerneighoring relationshipsin overlay network2: Application Layer85Comparing Client-server, P2P architecturesQuestion: How much time distribute file initially at one server to N other computers?usu2d1d2u1uNdNServerNetwork (with abundant bandwidth)File, size Fus:server upload bandwidthui:client/peer i upload bandwidthdi:client/peer i download bandwidth2: Application Layer86Client-server: file distribution timeusu2d1d2u1uNdNServerNetwork (with abundant bandwidth)Fserver sequentially sends N copies:NF/ustime client i takes F/di time to downloadincreases linearly in N(for large N)= dcs= max {NF/us, F/min(di)}iTime to distribute Fto Nclients using client/server approach 2: Application Layer87P2P: file distribution timeusu2d1d2u1uNdNServerNetwork (with abundant bandwidth)Fserver must send one copy: F/ustime 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 peer): us+ Suii=1,NdP2P= max {F/us, F/min(di), NF/(us+ Sui) }ii=1,N2: Application Layer8800.511.522.533.505101520253035NMinimum Distribution TimeP2PClient-ServerComparing Client-server, P2P architectures2: Application Layer89P2P Case Study: BitTorrent tracker:tracks peers participating in torrenttorrent:group of peers exchanging chunks of a fileobtain listof peerstrading chunkspeerP2P file distribution2: Application Layer90BitTorrent (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) remain2: Application Layer91BitTorrent (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 issues requests for her missing chunksrarest firstSending Chunks: tit-for-tatAlice sends chunks to four neighbors currently sending her chunks at the highest ratere-evaluate top 4 every 10 secsevery 30 secs: randomly select another peer, starts sending chunksnewly chosen peer may join top 42: Application Layer92P2P Case study: SkypeP2P (pc-to-pc, pc-to-phone, phone-to-pc) Voice-Over-IP (VoIP) application also IMproprietary application-layer protocol (inferred via reverse engineering) hierarchical overlaySkype clients (SC)Supernode (SN)Skype login server2: Application Layer93Skype: making a callUser starts SkypeSkype login serverSC registers with SNlist of bootstrap SNsSC logs in (authenticate)Call: SC contacts SN will callee IDSN contacts other SNs (unknown protocol, maybe flooding) to find addr of callee; returns addr to SCSC directly contacts callee, overTCP2: Application Layer94Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2: Application Layer95Socket programmingSocket APIintroduced in BSD4.1 UNIX, 1981explicitly created, used, released by apps client/server paradigm two types of transport service via socket API: unreliable datagram reliable, byte stream-oriented a host-local, application-created, OS-controlledinterface (a “door”) into whichapplication process can both send and receivemessages to/from another application processsocketGoal:learn how to build client/server application that communicate using sockets2: Application Layer96Socket-programming using TCPSocket:a door between application process and end-end-transport protocol (UCP or TCP)TCP service:reliable transfer of bytesfrom one process to anotherprocessTCP withbuffers,variablessocketcontrolled byapplicationdevelopercontrolled byoperatingsystemhost orserverprocessTCP withbuffers,variablessocketcontrolled byapplicationdevelopercontrolled byoperatingsystemhost orserverinternet2: Application Layer97Socket programming with TCPClient must contact serverserver process must first be runningserver must have created socket (door) that welcomes client’s 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 TCPWhen contacted by client, server TCP creates new socketfor 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-ordertransfer of bytes (“pipe”) between client and serverapplication viewpoint2: Application Layer98Client/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 Layer99outToServerto networkfrom networkinFromServerinFromUserkeyboardmonitorProcessclientSocketinputstreaminputstreamoutputstreamTCPsocketClientprocessclient TCP socketStream jargonA streamis a sequence of characters that flow into or out of a process.An input streamis attached to some input source for the process, e.g., keyboard or socket.An output streamis attached to an output source, e.g., monitor or socket.2: Application Layer100Socket programming with TCPExample client-server app:1) client reads line from standard input (inFromUserstream) , sends to server via socket (outToServerstream)2) server reads line from socket3) server converts line to uppercase, sends back to client4) client reads, prints modified line from socket (inFromServerstream)2: Application Layer101Example: 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 Layer102Example: Java client (TCP), cont.BufferedReader inFromServer = new BufferedReader(newInputStreamReader(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 Layer103Example: 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(newInputStreamReader(connectionSocket.getInputStream())); Createwelcoming socketat port 6789Wait, on welcomingsocket for contactby clientCreate inputstream, attached to socket2: Application Layer104Example: Java server (TCP), contDataOutputStream 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 connection2: Application Layer105Chapter 2: Application layer2.1 Principles of network applications2.2 Web and HTTP2.3 FTP 2.4 Electronic MailSMTP, POP3, IMAP2.5 DNS2.6 P2P file sharing2.7 Socket programming with TCP2.8 Socket programming with UDP2.9 Building a Web server2: Application Layer106Socket programming with UDPUDP: 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 packetUDP: transmitted data may be received out of order, or lostapplication viewpointUDP provides unreliabletransferof groups of bytes (“datagrams”)between client and server2: Application Layer107Client/server socket interaction: UDPcloseclientSocketServer (running on hostid)read reply fromclientSocketcreate socket,clientSocket = DatagramSocket()ClientCreate, address (hostid, port=x,send datagram request using clientSocketcreate socket,port=x, forincoming request:serverSocket = DatagramSocket()read request fromserverSocketwrite reply toserverSocketspecifying clienthost address,port number2: Application Layer108Example: Java client (UDP)sendPacketto networkfrom networkreceivePacketinFromUserkeyboardmonitorProcessclientSocketUDPpacketinputstreamUDPpacketUDPsocketOutput: sends packet (recallthat TCP sent “byte stream”)Input: receives packet (recall thatTCP received “byte stream”)Clientprocessclient UDP socket2: Application Layer109Example: 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 socketTranslatehostname to IP address using DNS2: Application Layer110Example: 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, portSend datagramto serverRead datagramfrom server2: Application Layer111Example: 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 Layer112Example: Java server (UDP), contString 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 client2: Application Layer113Chapter 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 Layer114Chapter 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 edge”
MissPowerPoint 2/29/2008 |
280 |
40 |
0 |
technology
MissPowerPoint 2/29/2008 |
695 |
52 |
0 |
technology
MissPowerPoint 2/29/2008 |
293 |
37 |
0 |
technology
MissPowerPoint 2/29/2008 |
332 |
59 |
0 |
technology
MissPowerPoint 2/29/2008 |
442 |
70 |
0 |
technology
MissPowerPoint 2/29/2008 |
281 |
39 |
0 |
technology
BeunaventuraLongjas 9/9/2008 |
53 |
1 |
0 |
business
itscooligotit 9/8/2008 |
54 |
2 |
0 |
business
MissPowerPoint 2/29/2008 |
238 |
26 |
0 |
technology
MissPowerPoint 2/29/2008 |
234 |
13 |
0 |
technology
MissPowerPoint 2/29/2008 |
129 |
7 |
0 |
technology
jasonpatino 1/16/2008 |
302 |
12 |
0 |
technology
MaryJeanMenintigar 9/10/2008 |
59 |
6 |
0 |
business
BeunaventuraLongjas 8/29/2008 |
75 |
3 |
0 |
business
MissPowerPoint 10/11/2008 |
8 |
0 |
0 |
BUZZ
MissPowerPoint 10/11/2008 |
6 |
0 |
0 |
educational
MissPowerPoint 10/11/2008 |
5 |
0 |
0 |
educational
MissPowerPoint 10/11/2008 |
7 |
0 |
0 |
educational
MissPowerPoint 10/11/2008 |
6 |
0 |
0 |
educational
MissPowerPoint 10/11/2008 |
2 |
0 |
0 |
educational
MissPowerPoint 10/11/2008 |
9 |
1 |
0 |
educational
MissPowerPoint 10/11/2008 |
9 |
0 |
0 |
educational
MissPowerPoint 10/11/2008 |
8 |
0 |
0 |
educational
MissPowerPoint 10/11/2008 |
12 |
0 |
0 |
BUZZ