/
Part 2: Application Layer Part 2: Application Layer

Part 2: Application Layer - PowerPoint Presentation

melanie
melanie . @melanie
Follow
69 views
Uploaded On 2023-06-24

Part 2: Application Layer - PPT Presentation

CSE 34615461 Reading Chapter 2 Kurose and Ross 1 Chapter 2 Outline Principles of Network Applications Web and HTTP FTP Email SMTP POP3 IMAP DNS P2P Applications Video Streaming Socket Programming with UDP and TCP ID: 1002862

client server sock http server client http sock message dns socket file port request data msg tcp mail peer

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Part 2: Application Layer" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. Part 2: Application LayerCSE 3461/5461Reading: Chapter 2, Kurose and Ross1

2. Chapter 2: OutlinePrinciples of Network ApplicationsWeb and HTTPFTPEmail: SMTP, POP3, IMAPDNSP2P ApplicationsVideo StreamingSocket Programming with UDP and TCP2

3. 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 / IMAPDNSCreating network applicationsSocket API3

4. Example Network AppsE-mailWebText messagingRemote loginP2P file sharingMulti-user network gamesStreaming stored video (YouTube, Hulu, Netflix) Voice over IP (e.g., Skype)Real-time video conferencingSocial networkingSearch……4

5. 5Creating a Network AppWrite programs that:Run 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 linkphysical

6. Application ArchitecturesPossible structure of applications:Client-serverPeer-to-peer (P2P)6

7. Client-Server ArchitectureServer: Always-on hostPermanent IP addressCan be in data centers, for scalabilityClients:Communicate with serverMay be intermittently connectedMay have dynamic IP addressesDo not communicate directly with each other7client/server

8. P2P ArchitectureNo always-on serverArbitrary end systems directly communicatePeers request service from other peers, provide service in return to other peersSelf-scalability – new peers bring new service capacity, as well as new service demandsPeers are intermittently connected and change IP addressesComplex management8peer-to-peer

9. Communicating ProcessesProcess: Program running within a hostWithin 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 contacted9Aside: applications with P2P architectures have client processes and server processesClients and Servers

10. SocketsProcess 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 to deliver message to socket at receiving process10InternetControlledby OSControlled byapp developertransportapplicationphysicallinknetworkprocesstransportapplicationphysicallinknetworkprocessSocket

11. Addressing ProcessesIdentifier includes both IP address and port numbers associated 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…To receive messages, process must have identifierHost device has unique 3 bit IP addressQ: Does IP address of host on which process runs suffice for identifying the process?11

12. An App-Layer Protocol Defines:Types 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 messagesOpen protocols:Defined in RFCsAllows for interoperabilitye.g., HTTP, SMTPProprietary protocols:e.g., Skype12

13. What Transport Service does an App Need?Data integritySome apps (e.g., file transfer, web transactions) require 100% reliable data transfer Other apps (e.g., audio) can tolerate some lossTimingSome apps (e.g., Internet telephony, interactive games) require low delay to be “effective”13ThroughputSome apps (e.g., multimedia) need minimum throughput to be “effective”Other apps (“elastic apps”) use whatever throughput they get SecurityEncryption, data integrity, …

14. Transport Service Requirements: Common Apps14ApplicationData LossThroughputTime-SensitiveFile transferNo lossElasticNoEmailNo lossElasticNoWeb documentsNo lossElasticNoReal-time audio/videoLoss-tolerantAudio: 5 kbps–1 Mbps; Video: 10 kbps–5 MbpsYes, ~100 msecStored audio/videoLoss-tolerantSame as aboveYes, few secInteractive gamesLoss-tolerantAt least few kbpsYes, ~100 msecText messagesNo lossElasticYes, no

15. Internet Apps: Application, Transport Protocols15ApplicationApplication Layer ProtocolUnderlying Transport ProtocolEmailSMTP [RFC 2821]TCPRemote terminal accessTelnet [RFC 854]TCPWebHTTP [RFC 2616]TCPFile transferFTP [RFC 959]TCPStreaming multimediaHTTP (e.g., YouTube), RTP [RFC 1889]TCP or UDPInternet telephonySIP, RTP, proprietary (e.g., Skype)TCP or UDP

16. Chapter 2: OutlinePrinciples of Network ApplicationsWeb and HTTPFTPEmail: SMTP, POP3, IMAPDNSP2P ApplicationsVideo StreamingSocket Programming with UDP and TCP16

17. The WebWeb page:Consists of “objects”Addressed by a URLMost Web pages consist of:Base HTML page, andSeveral referenced objects.URL has two components: host name and path nameUser agent for Web is called a browser:MS Internet ExplorerFirefoxGoogle ChromeSafariServer for Web is called Web server:Apache (public domain)Nginx (BSD)MS Internet Information Server (proprietary)17

18. The Web: the HTTP ProtocolHTTP: 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 2068HTTP 2.0: RFC 7540HTTP 3.0 in development…18PC runningExplorerServer runningWebserverMac runningFirefoxHTTP requestHTTP requestHTTP responseHTTP response

19. The HTTP Protocol (more)HTTP: TCP transport service: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 requests19Protocols that maintain “state” are complex!Past history (state) must be maintainedIf server/client crashes, their views of “state” may be inconsistent, must be reconciledAside

20. HTTP Example (1)Suppose user enters URL http://www.someschool.edu/aDepartment/index.html1a. HTTP client initiates TCP connection to http server (process) at www.someschool.edu. Port 80 is default for HTTP server.202. HTTP client sends http request message (containing URL) into TCP connection socket1b. HTTP server at host www.someschool.edu waiting for TCP connection at port 80. “Accepts” connection, notifies client3. HTTP server receives request message, forms response message containing requested object (aDepartment/index.html), sends message into sockettime(Contains text, references to 10 JPEG images)

21. HTTP Example (2)5. HTTP client receives response message containing HTML file, displays HTML. Parsing HTML file, finds 10 referenced JPEG objects216. Steps 1–5 repeated for each of 10 JPEG objects4. HTTP server closes TCP connection. time

22. Non-Persistent and Persistent ConnectionsNon-persistentHTTP/1.0Server parses request, responds, and closes TCP connection2 RTTs to fetch each objectEach object transfer suffers from TCP’s slow startPersistentDefault for HTTP/1.1On same TCP connection: server, parses request, responds, parses new request, …Client sends requests for all referenced objects as soon as it receives base HTML.Fewer RTTs and less slow start.22But most browsers useparallel TCP connections.

23. HTTP Message Format: RequestTwo types of HTTP messages: request, responseHTTP request message:ASCII (human-readable format)23GET /somedir/page.html HTTP/1.0 User-agent: Mozilla/4.0 Accept: text/html, image/gif,image/jpeg Accept-language:fr (extra carriage return, line feed) request line(GET, POST, HEAD commands)header linesCarriage return, line feed indicates end of message

24. HTTP Request Message: General Format24

25. HTTP Message Format: Response25HTTP/1.0 200 OK Date: 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 file

26. HTTP 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 Supported26In first line in server → client response message.A few sample codes:

27. Try HTTP (Client Side) for Yourself1. Telnet to your favorite Web server:27Opens TCP connection to port 80 (default HTTP server port) at www.cse.ohio-state.edu.Anything typed in sent to port 80 at www.cse.ohio-state.edutelnet www.cse.ohio-state.edu/ 802. Type in a GET HTTP request:GET /~champion/index.html HTTP/1.0By typing this in (hit carriagereturn twice), you sendthis minimal (but complete) GET request to HTTP server3. Look at response message sent by HTTP server!

28. User-Server State: Cookies (1)Many websites use cookiesFour components:Cookie header line of HTTP response messageCookie header line in next HTTP request messageCookie file kept on user’s host, managed by user’s browserBack-end database at websiteExample:Susan always accesses the Internet from PCVisits specific e-commerce site for first timeWhen initial HTTP requests arrives at site, site creates: Unique IDEntry in backend database for ID28

29. User-Server State: Cookies (2)29ClientServerUsual 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-specificactionAccessebay 8734amazon 1678Backenddatabase

30. User-Server State: Cookies (3)Use cases with cookies:AuthorizationShopping cartsRecommendationsUser session state (web e-mail)30Cookies and privacy:Cookies permit sites to learn a lot about youYou may supply name and e-mail to sitesAsideHow to maintain “state”:Protocol endpoints: maintain state at sender/receiver over multiple transactionsCookies: HTTP messages carry state

31. Web Caching (1)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 client31Goal: Satisfy client request without involving origin serverClientWeb cache(proxy server)ClientHTTP requestHTTP responseHTTP requestHTTP requestOrigin serverOrigin serverHTTP responseHTTP response

32. Web Caching (2)Cache acts as both client and serverServer for original requesting clientClient to origin 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 linkInternet dense with caches: enables “poor” content providers to effectively deliver content (so too does P2P file sharing)32

33. Web Caching Example (1) 33originserversPublic InternetInstitutionalnetwork1 Gbps LAN1.54 Mbps access linkAssumptions:Avg object size: 100 KbitsAvg request rate from browsers to origin servers: 15/secAvg data rate to browsers: 1.50 MbpsRTT from institutional router to any origin server: 2 secAccess link rate: 1.54 MbpsConsequences:LAN utilization: 0.15%Access link utilization = 99%Total delay = Internet delay + access delay + LAN delay = 2 sec + minutes + microsecondsproblem!

34. 34Web Caching Example (2)Assumptions:Avg object size: 100 KbitsAvg request rate from browsers to origin servers: 15/secAvg data rate to browsers: 1.50 MbpsRTT from institutional router to any origin server: 2 secAccess link rate: 1.54 MbpsConsequences:LAN utilization: 0.15%Access link utilization = 99%Total delay = Internet delay + access delay + LAN delay = 2 sec + minutes + usecsoriginservers1.54 Mbps access link154 Mbps154 MbpsmsecsCost: increased access link speed (not cheap!)9.9%Public InternetInstitutionalnetwork1 Gbps LAN

35. Institutionalnetwork1 Gbps LAN35Web Caching Example (3)originservers1.54 Mbps access linkLocal web cacheAssumptions:Avg object size: 100 KbitsAvg request rate from browsers to origin servers: 15/secAvg data rate to browsers: 1.50 MbpsRTT from institutional router to any origin server: 2 secAccess link rate: 1.54 MbpsConsequences:LAN utilization: 0.15%Access link utilization = 100%Total delay = Internet delay + access delay + LAN delay = 2 sec + minutes + usecs??How to compute link utilization, delay?Cost: Web cache (cheap!)Public Internet

36. 36Web Caching Example (4)Calculating access link utilization, delay with cache:Suppose cache hit rate is 0.440% requests satisfied at cache, 60% requests satisfied at origin originservers1.54 Mbps access linkAccess link utilization: 60% of requests use access link Data rate to browsers over access link = 0.6*1.50 Mbps = 0.9 Mbps Utilization = 0.9/1.54 = 0.58Total delay= 0.6 * (delay from origin servers) +0.4 * (delay when satisfied at cache)= 0.6 (2.01) + 0.4 (~msecs) = ~ 1.2 secsLess than with 154 Mbps link (and cheaper too!)Public InternetInstitutionalnetwork1 Gbps LANLocal web cache

37. Conditional GET Goal: don’t send object if cache has up-to-date cached versionNo object transmission delayLower link utilizationCache: specify date of cached copy in HTTP requestIf-modified-since: <date>Server: response contains no object if cached copy is up-to-date: HTTP/1.0 304 not modified37HTTP request msgIf-modified-since: <date>HTTP responseHTTP/1.0 304 Not ModifiedObject not modifiedbefore<date>HTTP request msgIf-modified-since: <date>HTTP responseHTTP/1.0 200 OK<data>Object modifiedafter <date>ClientServer

38. HTTP Versions 2, 3Max. webpage latency: 250–300 msec (lower is better!)HTTP 2, 3 designed for security, performanceHTTP 2: Supports encryption as “first-class citizen”More info: I. Gregorik, High Performance Browser Networking, https://hpbn.co/http2/ (Chapter 12)HTTP 3:Uses Google’s QUIC transport protocol (UDP) for lower latencyMore info: http://www.chromium.org/quic; A. Langley et al., “The QUIC Transport Protocol,” Proc. ACM SIGCOMM, 2017; https://www.zdnet.com/article/http-over-quic-to-be-renamed-http3/ 38

39. Chapter 2: OutlinePrinciples of Network ApplicationsWeb and HTTPFTPEmail: SMTP, POP3, IMAPDNSP2P ApplicationsVideo StreamingSocket Programming with UDP and TCP39

40. FTP: File Transfer Protocol40File transferFTPserverFTPuserinterfaceFTPclientLocal filesystemRemote filesystemUser at hostTransfer file to/from remote hostClient/server modelClient: side that initiates transfer (either to/from remote)Server: remote hostFTP server: port 21

41. FTP: Separate Control, Data ConnectionsFTP client contacts FTP server at port 21, using TCP Client authorized over control connectionClient browses remote directory, sends commands over control connectionWhen server receives file transfer command, server opens 2nd TCP data connection (for file) to clientAfter transferring one file, server closes data connection41FTPclientFTPserverTCP control connection,server port 21TCP data connection,server port 20Server opens another TCP data connection to transfer another fileControl connection: “out of band”FTP server maintains “state”: current directory, earlier authentication

42. FTP 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 can’t open data connection452 error writing file42

43. Chapter 2: OutlinePrinciples of Network ApplicationsWeb and HTTPFTPEmail: SMTP, POP3, IMAPDNSP2P ApplicationsVideo StreamingSocket Programming with UDP and TCP43

44. EmailThree major components: User agents Mail servers Simple mail transfer protocol: SMTPUser agent:a.k.a. “Mail reader”Composing, editing, reading mail messagese.g., Outlook, Thunderbird, iPhone mail clientOutgoing, incoming messages stored on server44User mailboxOutgoing message queueMailServerMailServerMailServerSMTPSMTPSMTPUserAgentUserAgentUserAgentUserAgentUserAgentUserAgent

45. Email: 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 server“Server”: receiving mail server45MailServerMailServerMailServerSMTPSMTPSMTPUserAgentUserAgentUserAgentUserAgentUserAgentUserAgent

46. Email: SMTPUses 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 interaction (like HTTP, FTP)Commands: ASCII textResponse: status code and phraseMessages must be in 7-bit ASCII46

47. Scenario: Alice Sends Message to Bob1) Alice uses UA (user agent) to compose message “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 UA to read message47UserAgentMailServerMailServer123456Alice’s mail serverBob’s mail serverUserAgent

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

49. SMTP: Final WordsSMTP uses persistent connectionsSMTP requires message (header & body) to be in 7-bit ASCIIComparison with HTTP:HTTP: pullSMTP: pushBoth have ASCII command/response interaction, status codesHTTP: each object encapsulated in its own response messageSMTP: multiple objects sent in multipart message49

50. Mail Message FormatSMTP: protocol for exchanging email messagesHeader lines, e.g.,To:From:Subject:Different from SMTP MAIL FROM, RCPT TO: commands!Body: the “message” ASCII characters only50HeaderBodyblankline

51. Mail Access ProtocolsSMTP: delivery/storage to receiver’s serverMail access protocol: retrieval from serverPOP: Post Office Protocol: authorization, download IMAP: Internet Mail Access Protocol: more features, including manipulation of stored messages on serverHTTP: Gmail, Hotmail, Yahoo! Mail, etc.51Sender’s mail serverSMTPSMTPMail accessprotocolReceiver’s mail server(e.g., POP, IMAP)UserAgentUserAgent

52. POP3 ProtocolAuthorization phaseClient commands: User: declare usernamePass: passwordServer responses+Ok-ErrTransaction phase, client:List: list message numbersRetr: retrieve message by numberDele: deleteQuit52 C: list S: 1 498 S: 2 912 S: . C: retr 1 S: <message 1 contents> S: . C: dele 1 C: retr 2 S: <message 1 contents> 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 on

53. POP3 and IMAPMore about POP3Previous example uses POP3 “download and delete” modeBob cannot re-read e-mail if he changes clientPOP3 “download-and-keep”: copies of messages on different clientsPOP3 is stateless across sessionsIMAPKeeps all messages in one place: at serverAllows user to organize messages in foldersKeeps user state across sessions:Names of folders and mappings between message IDs and folder names53

54. Chapter 2: OutlinePrinciples of Network ApplicationsWeb and HTTPFTPEmail: SMTP, POP3, IMAPDNSP2P ApplicationsVideo StreamingSocket Programming with UDP and TCP54

55. DNS: Domain Name SystemPeople: Many identifiers:SSN, name, passport #Internet hosts, routers:IP address (32 bit) - used for addressing datagrams“Name”, e.g., www.yahoo.com - used by humansQ: How to map between IP address and name, and vice versa ?Domain name system:Distributed database implemented in hierarchy of many name serversApplication-layer protocol: hosts, name servers communicate to resolve names (address/name translation)Note: core Internet function, implemented as application-layer protocolComplexity at network’s “edge”55

56. DNS: Services and Structure DNS servicesHostname to IP address translationHost aliasingCanonical, alias namesMail server aliasingLoad distributionReplicated web servers: many IP addresses correspond to one nameWhy not centralize DNS?Single point of failureTraffic volumeDistant centralized databaseMaintenance56

57. DNS: Distributed, Hierarchical DatabaseClient wants IP for www.amazon.com; 1st approximation:Client queries 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.com57Root DNS Servers.com DNS servers.org DNS servers.edu DNS serverspoly.eduDNS serversumass.eduDNS serversyahoo.comDNS serversamazon.comDNS serverspbs.orgDNS servers……

58. DNS: 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 server5813 root name “servers” worldwide (replicated for load balancing)a. Verisign, Los Angeles CA (5 other sites)b. USC-ISI Marina del Rey, CAl. ICANN Los Angeles, CA (41 other sites)e. NASA Mt View, CAf. Internet Software C.Palo Alto, CA (and 48 other sites)i. Netnod, Stockholm (37 other sites)k. RIPE London (17 other sites)m. WIDE Tokyo(5 other sites)c. Cogent, Herndon, VA (5 other sites)d. U Maryland College Park, MDh. ARL Aberdeen, MDj. Verisign, Dulles VA (69 other sites )g. US DoD Columbus, OH (5 other sites)

59. TLD, Authoritative ServersTop-level domain (TLD) servers:Responsible for .com, .org, .net, .edu, .aero, .jobs, .museums, and all top-level country domains, e.g.: uk, fr, ca, jpVerisign maintains servers for .com TLDEducause for .edu TLDAuthoritative DNS servers: Organization’s own DNS server(s), providing authoritative hostname to IP mappings for organizations named hosts Can be maintained by organization or service provider59

60. Local DNS Name ServerEach ISP (residential ISP, company, university) has oneAlso called “default name server”When host makes DNS query, query is sent to its local DNS serverHas local cache of recent name-to-address translation pairs (but may be out of date!)Acts as proxy, forwards query into hierarchy60

61. DNS Name Resolution Example (1)Host at cis.poly.edu wants IP address for gaia.cs.umass.edu61Requesting hostcis.poly.edugaia.cs.umass.eduroot DNS serverLocal DNS serverdns.poly.edu123456authoritative DNS serverdns.cs.umass.edu78TLD DNS serverIterated query: Contacted server replies with name of server to contact “I don’t know this name, but ask this server”

62. 624563Recursive query:Puts burden of name resolution on contacted name serverHeavy load at upper levels of hierarchy?requesting hostcis.poly.edugaia.cs.umass.eduroot DNS serverlocal DNS serverdns.poly.edu127authoritative DNS serverdns.cs.umass.edu8DNS Name Resolution Example (2)TLD DNS server

63. DNS: Caching, Updating RecordsOnce (any) name server learns mapping, it caches mappingCache entries timeout (disappear) after some time (time to live (TTL))TLD servers typically cached in local name serversThus root name servers not often visitedCached entries may be out-of-date (best effort name-to-address translation!)If name host changes IP address, may not be known internet-wide until all TTLs expire63

64. DNS RecordsDNS: distributed DB storing resource records (RR)type: NSname is domain (e.g., Foo.Com)value is hostname of authoritative name server for this domain64RR format: (name, value, type, ttl)type: Aname is hostnamevalue is IP addresstype: CNAMEname is alias name for some “canonical” (the real) namewww.ibm.com is really servereast.backup2.ibm.comvalue is canonical nametype: MXvalue is name of mail server associated with name

65. DNS Protocol, Messages (1)Query and reply messages, both with same message format65Msg headerIdentification: 16 bit # for query, reply to query uses same #Flags:query or replyrecursion desired recursion availablereply is authoritativeIdentificationFlags# questionsQuestions (variable # of questions)# additional RRs# authority RRs# answer RRsAnswers (variable # of RRs)Authority (variable # of RRs)Additional info (variable # of RRs)2 bytes2 bytes

66. 66Name, type fields for a queryRRs in responseto queryRecords forauthoritative serversAdditional “helpful”info that may be usedIdentificationFlags# questionsQuestions (variable # of questions)# additional RRs# authority RRs# answer RRsAnswers (variable # of RRs)Authority (variable # of RRs)Additional info (variable # of RRs)DNS Protocol, Messages (2)2 bytes2 bytes

67. Inserting Records into DNSExample: new startup “network utopia”Register name networkutopia.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.networkutopia.com; type MX record for networkutopia.com67

68. Attacking DNSDDoS attacksBombard root servers with trafficNot successful to dateTraffic filteringLocal DNS servers cache IPs of TLD servers, allowing root server bypassBombard TLD serversPotentially more dangerousRedirect AttacksMan-in-middleIntercept queriesDNS poisoningSend bogus replies to DNS server, which cachesExploit DNS for DDoSSend queries with spoofed source address: target IP68

69. Chapter 2: OutlinePrinciples of Network ApplicationsWeb and HTTPFTPEmail: SMTP, POP3, IMAPDNSP2P ApplicationsVideo StreamingSocket Programming with UDP and TCP69

70. Pure P2P ArchitectureNo always-on serverArbitrary end systems directly communicatePeers are intermittently connected and change IP addressesExamples:File distribution (BitTorrent)Streaming (KanKan)VoIP (Skype) 70

71. File Distribution: Client-Server vs. P2PQuestion: how long to distribute file (size F) from one server to N peers?Peer upload/download capacity is limited resource71usuNdNserverNetwork (with abundant bandwidth)file, size Fus : server upload capacityui : peer i upload capacitydi : peer i download capacityu2d2u1d1diui

72. File Distribution Time: Client-ServerServer transmission: must sequentially send (upload) N file copies:Time to send one copy: F/us Time to send N copies: NF/us72Increases linearly with NTime to distribute F to N clients using client-server approach Client: each client must download file copydmin = min client download rateMax client download time: F/dmin usNetworkdiuiF

73. 73File Distribution Time: P2PServer transmission: must upload at least one copyTime to send one copy: F/us Time to distribute F to N clients using P2P approach usNetworkdiuiFClient: each client must download file copyMin client download time: F/dmin Clients: as aggregate must download NF bitsMax upload rate (limiting max download rate) is:… but so does this, as each peer brings service capacityIncreases linearly in N …

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

75. P2P File Distribution: BitTorrent 75Tracker: tracks peers participating in torrentTorrent: group of peers exchanging chunks of a fileAlice arrives …File divided into 256 KB chunksPeers in torrent send/receive file chunks… obtains listof peers from tracker… and begins exchanging file chunks with peers in torrent

76. Peer joining torrent: Has no chunks, but will accumulate them over time from other peersRegisters with tracker to get list of peers, connects to subset of peers (“neighbors”)76P2P File Distribution: BitTorrent While downloading, peer uploads chunks to other peersPeer may change peers with whom it exchanges chunksChurn: peers may come and goOnce peer has entire file, it may (selfishly) leave or (altruistically) remain in torrent

77. BitTorrent: Requesting, Sending File ChunksRequesting chunks:At any given time, different peers have different subsets of file chunksPeriodically, Alice asks each peer for list of chunks that they haveAlice requests missing chunks from peers, rarest first77Sending chunks: tit-for-tatAlice sends chunks to those four peers currently sending her chunks at highest rate Other peers are choked by Alice (do not receive chunks from her)Re-evaluate top 4 every 10 sEvery 30 s: randomly select another peer, starts sending chunks“Optimistically unchoke” this peerNewly chosen peer may join top 4

78. BitTorrent: Tit-for-Tat78(1) Alice “optimistically unchokes” Bob(2) Alice becomes one of Bob’s top-four providers; Bob reciprocates(3) Bob becomes one of Alice’s top-four providersHigher upload rate: Find better trading partners, get file faster !

79. Distributed Hash Table (DHT)DHT: a distributed P2P databaseDatabase has (key, value) pairs; examples: Key: ss number; value: human nameKey: movie title; value: IP addressDistribute the (key, value) pairs over the (millions of peers)A peer queries DHT with keyDHT returns values that match the keyPeers can also insert (key, value) pairs79

80. Q: How to Assign Keys to Peers?Central issue:Assigning (key, value) pairs to peers.Basic idea: Convert each key to an integerAssign integer to each peerPut (key, value) pair in the peer that’s closest to the key80

81. DHT IdentifiersAssign integer identifier to each peer in range Each identifier represented by n bits.Require each key to be an integer in same rangeTo get integer key, hash original keye.g., key = hash(“Debian Linux”)This is why it’s referred to as a distributed “hash” table81

82. Assign Keys to PeersRule: assign key to the peer that has the closest ID.Convention in lecture: closest is the immediate successor of the key.E.G., N = 4; peers: 1,3,4,5,8,10,12,14; Key = 13, then successor peer = 14Key = 15, then successor peer = 182

83. 13458101215Circular DHT (1)Each peer only aware of immediate successor and predecessor.“Overlay network”83

84. 00010011010001011000101011001111Who’s responsiblefor key 14 (1110)?I amO(N) messageson average to resolvequery, when thereare N peers111011101110111011101110Define closestas closestsuccessorCircular DHT (2)8413458101215

85. Circular 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 query8513458101215Who’s responsible for key 14 (1110)?

86. Peer ChurnExample 1: Peer 5 abruptly leaves. What happens?Example 2: Peer 13 wants to join. What happens?8613458101215Peers may come and go (churn)Each peer knows address of its two successors Each peer periodically pings its two successors to check alivenessIf immediate successor leaves, choose next successor as new immediate successor

87. Chapter 2: OutlinePrinciples of Network ApplicationsWeb and HTTPFTPEmail: SMTP, POP3, IMAPDNSP2P ApplicationsVideo StreamingSocket Programming with UDP and TCP87

88. Video Streaming and CDNs: ContextVideo traffic: major consumer of Internet bandwidthNetflix, YouTube: 37%, 16% of downstream residential ISP traffic~1B YouTube users, ~75M Netflix usersChallenge: scale – how to reach ~1B users?Single mega-video server won’t work (why?)Challenge: heterogeneityDifferent users have different capabilities (e.g., wired versus mobile; bandwidth-rich versus bandwidth-poor)Solution: distributed, application-level infrastructure

89. Multimedia: Video (1)Video: sequence of images displayed at constant ratee.g., 24 images/secDigital image: array of pixelsEach pixel represented by bitsCoding: use redundancy within and between images to decrease # bits used to encode imageSpatial (within image)Temporal (from one image to next)……………………..Spatial coding example: instead of sending N values of same color (all purple), send only two values: color value (purple) and number of repeated values (N)……………….…….Frame iFrame i + 1Temporal coding example: instead of sending complete frame at i + 1, send only differences from frame i

90. Multimedia: Video (2)CBR (Constant Bit Rate): video encoding rate fixedVBR (Variable Bit Rate): video encoding rate changes as amount of spatial, temporal coding changes Examples:MPEG-1 (CD-ROM):1.5 MbpsMPEG-2 (DVD): 3–6 MbpsMPEG-4 (often used in Internet, < 1 Mbps)……………………..Spatial coding example: instead of sending N values of same color (all purple), send only two values: color value (purple) and number of repeated values (N)……………….…….Frame iFrame i + 1Temporal coding example: instead of sending complete frame at i + 1, send only differences from frame i

91. Streaming Stored VideoSimple scenario:Video server(stored video)ClientInternet

92. Streaming Multimedia: DASH (1)DASH: Dynamic, Adaptive Streaming over HTTPServer:Divides video file into multiple chunksEach chunk stored, encoded at different rates Manifest file: provides URLs for different chunksClient:Periodically measures server-to-client bandwidthConsulting manifest, requests one chunk at a time Chooses maximum coding rate sustainable given current bandwidthCan choose different coding rates at different points in time (depending on available bandwidth at time)

93. Streaming Multimedia: DASH (2)DASH: Dynamic, Adaptive Streaming over HTTP“Intelligence” at client: client determinesWhen to request chunk (so that buffer starvation, or overflow does not occur)What encoding rate to request (higher quality when more bandwidth available) Where to request chunk (can request from URL server that is “close” to client or has high available bandwidth)

94. Content Distribution Networks (1)Challenge: how to stream content (selected from millions of videos) to hundreds of thousands of simultaneous users?Option 1: single, large “mega-server”Single point of failurePoint of network congestionLong path to distant clientsMultiple copies of video sent over outgoing link… Quite simply: this solution doesn’t scale

95. Content Distribution Networks (2)Challenge: how to stream content (selected from millions of videos) to hundreds of thousands of simultaneous users?Option 2: store/serve multiple copies of videos at multiple geographically distributed sites (CDN)Enter deep: push CDN servers deep into many access networks Close to usersUsed by Akamai: 1,700 locationsBring home: smaller number (tens) of larger clusters in POPs near (but not within) access networksUsed by Limelight

96. CDN: stores copies of content at CDN nodes e.g. Netflix stores copies of Stranger ThingsSubscriber requests content from CDNDirected to nearby copy, retrieves contentMay choose different copy if network path congestedContent Distribution Networks (3)……………… Where’s S.T.?Manifest file

97. Content Distribution Networks (3)……………… Internet host-host communication as a serviceOTT challenges: coping with a congested InternetFrom which CDN node to retrieve content?Viewer behavior in presence of congestion?What content to place in which CDN node?“Over the top” (OTT)

98. CDN Content Access: A Closer LookBob (client) requests video http://netcinema.com/6Y7B23VVideo stored in CDN at http://KingCDN.com/NetC6y&B23Vnetcinema.comKingCDN.com11. Bob gets URL for video http://netcinema.com/6Y7B23Vfrom netcinema.com web page22. Resolve http://netcinema.com/6Y7B23Vvia Bob’s local DNSNetCinema’sauthoratative DNS33. Netcinema’s DNS returns URL http://KingCDN.com/NetC6y&B23V44&5. Resolve http://KingCDN.com/NetC6y&B23via KingCDN’s authoritative DNS, which returns IP address of KingCDN server with video56. Request video fromKingCDN server,streamed via HTTPKingCDN’sauthoritative DNSBob’s local DNSserver

99. Case Study: Netflix11. Bob manages Netflix accountNetflix registration,accounting serversAmazon cloudCDNserver 22. Bob browsesNetflix video33. Manifest filereturned for requested video4. DASH streamingUpload copies of multiple versions of video to CDN serversCDNserver CDNserver

100. Chapter 2: OutlinePrinciples of Network ApplicationsWeb and HTTPFTPEmail: SMTP, POP3, IMAPDNSP2P ApplicationsVideo StreamingSocket Programming with UDP and TCP100

101. Socket Programming Goal: learn how to build client/server applications that communicate using socketsSocket: door between application process and end-end-transport protocol 101InternetControlledby OSControlled byapp developertransportapplicationphysicallinknetworkprocesstransportapplicationphysicallinknetworkprocessSocket

102. Socket Programming Two socket types for two transport services:UDP: unreliable datagramTCP: reliable, byte stream-oriented 102Application Example:Client reads a line of characters (data) from its keyboard and sends the data to the server.The server receives the data and converts characters to uppercase.The server sends the modified data to the client.The client receives the modified data and displays the line on its screen.

103. Socket Programming with UDPUDP: no “connection” between client & serverNo handshaking before sending dataSender explicitly attaches IP destination address and port # to each packetRcvr extracts sender IP address and port# from received packetUDP: transmitted data may be lost or received out-of-orderApplication viewpoint:UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server103

104. Client/Server Socket Interaction: UDP104Closeclient_sockRead datagram fromclient_sock via recvfrom(. . .)Create socket:client_sock =socket(AF_INET, SOCK_DGRAM)Create datagram with server IP andport x; send datagram viaclient_sock.sendto(. . .)Create socket, bind to port x:serv_sock = socket(AF_INET, SOCK_DGRAM)serv_sock.bind((’’, x))Read datagram fromserv_sock via recvfrom(. . .)Write reply toserv_sockspecifying client address,port # (via sendto(. . .))Server (running on serverIP)Client

105. 105Example App: UDP Clientfrom socket import *serv_name = ‘hostname’serv_port = 12000client_sock = socket(AF_INET, SOCK_DGRAM)message = raw_input(’Input lowercase sentence:’)msg_bytes = message.encode(encoding=‘ascii’)client_sock.sendto(msg_bytes,(serv_name,serv_port))mod_msg_bytes, serv_addr = client_sock.recvfrom(1000)mod_msg = mod_msg_bytes.decode(encoding=‘ascii’)print(mod_msg)client_sock.close()Python UDPClientInclude Python’s socket libraryCreate UDP socket for serverGet user keyboard input Attach server name, port to message; send into socketPrint out received string, close socketRead reply characters fromsocket into string

106. 106Example App: UDP Serverfrom socket import *server_port = 12000server_sock = socket(AF_INET, SOCK_DGRAM)server_sock.bind(('', server_port))print(‘The server is ready to receive’)while 1: msg_bytes, client_addr = server_sock.recvfrom(1000) msg = msg_bytes.decode(encoding=‘ascii’) mod_msg = msg.upper() mod_msg_bytes = mod_msg.encode(encoding=‘ascii’) server_sock.sendto(mod_msg_bytes, client_addr)Python UDPServerCreate UDP socketBind socket to local port number 12000Loop foreverRead from UDP socket into message, getting client’s address (client IP and port)Send uppercase string back to this client

107. Socket 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 TCP socket, specifying IP address, port number of server processWhen client creates socket: client TCP establishes connection to server TCPWhen contacted by client, server TCP creates new socket for server process to communicate with that particular clientAllows server to talk with multiple clientsSource port numbers used to distinguish clients (more in chapter 3)107TCP provides reliable, in-orderbyte-stream transfer (“pipe”) between client and serverApplication Viewpoint:

108. Client/Server Socket Interaction: TCP108Wait for incomingconnection requestconn_sock, addr =serv_sock.accept()Create socket bound to port x for incoming request:serv_sock = socket(AF_INET, SOCK_STREAM)serv_sock.bind((‘’, x))serv_sock.listen(1)Create socket, connect to hostid, port xclient_sock = socket(AF_INET, SOCK_STREAM)client_sock.connect((hostid, x))Server (running on hostid)ClientSend request using client_sock (via send(. . .))Read request from conn_sock (via recv(. . .))Write reply to conn_sock (via send(. . .))TCP connection setupClose conn_sockRead reply from client_sock(via recv(. . .))Close client_sock

109. 109Example App: TCP Clientfrom socket import *serv_name = ‘servername’serv_port = 12000client_sock = socket(AF_INET, SOCK_STREAM)client_sock.connect((serverName,serverPort))msg = raw_input(‘Input lowercase sentence:’)msg_bytes = msg.encode(encoding=‘ascii’)client_sock.send(msg_bytes)mod_msg_bytes = client_sock.recv(1024)mod_msg = mod_msg_bytes.decode(encoding=‘ascii’)print(‘From Server:’ + mod_msg)clientSocket.close()Python TCPClientCreate TCP socket for server, remote port 12000No need to attach server name, port

110. 110Example App: TCP Serverfrom socket import *serv_port = 12000serv_sock = socket(AF_INET,SOCK_STREAM)serv_sock.bind((‘’,serv_port))serv_sock.listen(1)print ‘The server is ready to receive’while 1: conn_sock, addr = serverSocket.accept() msg_bytes = conn_sock.recv(1000) msg = msg_bytes.decode(encoding=‘ascii’) msg_mod = msg.upper() msg_mod_bytes = msg_mod.encode(encoding=‘ascii’) conn_sock.send(msg_mod_bytes) conn_sock.close()Python TCPServerCreate, bind TCP welcoming socketServer listens for incoming TCP requestsLoop foreverServer waits on accept()for incoming requests, new socket created on returnRead bytes from socket (but not address as in UDP)Close connection to this client (but not welcoming socket)

111. Part 2: SummaryApplication architectures:Client-serverP2PApp service requirements:Reliability, bandwidth, delayInternet transport service modelConnection-oriented, reliable: TCPUnreliable, datagrams: UDPOur study of network apps now complete!111Specific protocols:HTTPFTPSMTP, POP, IMAPDNSP2P: BitTorrent, DHT Socket programming: TCP, UDP sockets

112. Typical request/reply message exchange:Client requests info or serviceServer responds with data, status codeMessage formats:Headers: fields giving info about dataData: info being communicated112Important themes: Control vs. data messagesIn-band, out-of-bandCentralized vs. decentralized Stateless vs. statefulReliable vs. unreliable message transfer Complexity at network edgePart 2: SummaryMost importantly: learned about protocols!