Chapter 2 Application Layer A note on the use of these ppt slides: We re making these slides freely available to all (faculty, students, readers). They re in PowerPoint form so you can add, modify, and delete slides (including this one) and slide content to suit your needs. They obviously represent a lot of work on our part. In return for use, we only ask the following: 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. Computer Networking: A Top Down Approach, Jim Kurose, Keith Ross Addison-Wesley Thanks and enjoy! JFK/KWR All material copyright J.F Kurose and K.W. Ross, All Rights Reserved 2: Application Layer 1
Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2: Application Layer 2
Chapter 2: Application Layer Our goals: conceptual, implementation aspects of network application protocols transport-layer service models client-server paradigm peer-to-peer paradigm learn about protocols by examining popular application-level protocols HTTP FTP SMTP / POP3 / IMAP DNS programming network applications socket API 2: Application Layer 3
Some network apps e-mail web instant messaging remote login P2P file sharing multi-user network games streaming stored video clips voice over IP real-time video conferencing grid computing 2: Application Layer 4
Creating a network app write programs that run on (different) end systems communicate over network e.g., web server software communicates with browser software No need to write software for network-core devices Network-core devices do not run user applications applications on end systems allows for rapid app development, propagation application transport network data link physical application transport network data link physical application transport network data link physical 2: Application Layer 5
Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2.9 Building a Web server 2: Application Layer 6
Application architectures Client-server Peer-to-peer (P2P) Hybrid of client-server and P2P 2: Application Layer 7
Client-server architecture server: always-on 호스트 고정 (permanent) IP 주소 client/server clients: 서버와통신 Client 상호간직접통신하지는않음 간헐적으로네트워크에연결가능 동적 IP 주소가능 2: Application Layer 8
Pure P2P architecture always-on 서버가존재하지않음 단말상호간직접통신 peers are intermittently connected and change IP addresses peer-peer Highly scalable but difficult to manage 2: Application Layer 9
Hybrid of client-server and P2P Skype voice-over-ip P2P application centralized server: finding address of remote party: client-client connection: direct (not through server) 2011 년 MS 가 85 억불 (9.3 조원 ) 에인수 Instant messaging 사용자간의통신은 P2P 방식 centralized service: 사용자의 IP 주소확인은중앙서버에의존 사용자는 online 되었을때중앙서버에자신의 IP 주소를등록 사용자는통신하고자하는상대방의 IP 주소를중앙서버에문의해서알아냄 2: Application Layer 10
Processes communicating Process: program running within a host. within same host, two processes communicate using inter-process communication (defined by OS). processes in different hosts communicate by exchanging messages Client process: process that initiates communication Server process: process that waits to be contacted Note: applications with P2P architectures have client processes & server processes 2: Application Layer 11
Sockets process sends/receives messages to/from its socket socket analogous to door sending process shoves message out door sending process relies on transport infrastructure on other side of door which brings message to socket at receiving process host or server process socket TCP with buffers, variables controlled by app developer controlled by OS Internet host or server process socket TCP with buffers, variables API: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later) 2: Application Layer 12
Addressing processes Q: does IP address of host on which process runs suffice for identifying the process? Answer: NO, many processes can be running on same host 한호스트의프로세스가다른호스트의프로세스로메시지를전달하기위해서는수신프로세스를 identify 해야함 목적호스트의주소 목적호스트내의수신프로세스의 identifier Port number Example port numbers: HTTP server: 80 Mail server: 25 to send HTTP message to gaia.cs.umass.edu web server: IP address: 128.119.245.12 Port number: 80 more shortly 2: Application Layer 13
App-layer protocol defines Types of messages exchanged, e.g., request, response Message syntax: what fields in messages & how fields are delineated Message semantics meaning of information in fields Rules for when and how processes send & respond to messages Public-domain protocols: defined in RFCs allows for interoperability e.g., HTTP, SMTP Proprietary protocols: e.g., Skype 2: Application Layer 14
What transport service does an app need? Data loss 특정응용은 ( 예 : audio) 일정부분손실이발생해도 ok other apps (e.g., file transfer, telnet) require 100% reliable data transfer Timing 특정응용은 ( 예 : Internet telephony, interactive games) low delay 가필요 Throughput 특정응용은 ( 예 : 멀티미디어 ) 최소 throughput을요구 other apps ( elastic apps ) make use of whatever throughput they get Security Encryption, data integrity, 2: Application Layer 15
Transport service requirements of common apps Application Data loss Throughput Time Sensitive file transfer e-mail Web documents real-time audio/video stored audio/video interactive games instant messaging no loss no loss no loss loss-tolerant loss-tolerant loss-tolerant no loss elastic elastic elastic audio: 5kbps-1Mbps video:10kbps-5mbps same as above few kbps up elastic no no no yes, 100 s msec yes, few secs yes, 100 s msec yes and no 2: Application Layer 16
Internet transport protocols services TCP service: connection-oriented: setup required between client and server processes reliable transport between sending and receiving process flow control: sender won t overwhelm receiver congestion control: throttle sender when network overloaded does not provide: timing, minimum throughput guarantees, security UDP service: unreliable data transfer between sending and receiving process does not provide: connection setup, reliability, flow control, congestion control, timing, throughput guarantee, or security Q: why bother? Why is there a UDP? 2: Application Layer 17
Internet apps: application, transport protocols Application e-mail remote terminal access Web file transfer streaming multimedia Internet telephony Application layer 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) Underlying transport protocol TCP TCP TCP TCP TCP or UDP typically UDP DNS, SNMP: UDP 사용 2: Application Layer 18
Chapter 2: Application layer 2.1 Principles of network applications app architectures app requirements 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2: Application Layer 19
Web and HTTP First some jargon Web page consists of objects Object can be HTML file, JPEG image, Java applet, audio file, Web page consists of base HTML-file which includes several referenced objects Each object is addressable by a URL Example URL: www.someschool.edu/somedept/pic.gif host name path name 2: Application Layer 20
HTTP overview HTTP: hypertext transfer protocol 서버 HTTP 프로그램과 client HTTP 프로그램간의통신프로토콜 Brower와 Web 서버간의 Web page 전달을위해사용되나, Web page가 client 에서어떻게해석되는가와는아무관계없다. client/server model client: browser that requests, receives, displays Web objects server: Web server sends objects in response to requests HTTP 1.0: RFC 1945 HTTP 1.1: RFC 2068 PC running Explorer Mac running Navigator Web server must be always-on & has fixed IP address Server running Apache Web server 2: Application Layer 21
HTTP overview (continued) Uses TCP: client initiates TCP connection (creates socket) to server, port 80 server accepts TCP connection from client HTTP messages (applicationlayer protocol messages) exchanged between browser (HTTP client) and Web server (HTTP server) TCP connection closed HTTP is stateless server maintains no information about past client requests Client가수초내에동일한 object를다시요구해도, server는이 object를방금전에보냈다는사실을모르므로그냥다시보냄 aside Protocols that maintain state are complex! past history (state) must be maintained 2: Application Layer 22
HTTP connections Nonpersistent HTTP At most one object is sent over a TCP connection. Persistent HTTP Multiple objects can be sent over single TCP connection between client and server. 2: Application Layer 23
Nonpersistent HTTP Suppose user enters URL www.someschool.edu/somedepartment/home.index (contains text, references to 10 jpeg images) time 1a. HTTP client initiates TCP connection to HTTP server (process) at www.someschool.edu on port 80 2. HTTP client sends HTTP request message (containing URL) into TCP connection socket. Message indicates that client wants object somedepartment/home.index 1b. HTTP server at host www.someschool.edu waiting for TCP connection at port 80. accepts connection, notifying client 3. HTTP server receives request message, forms response message containing requested object, and sends message into its socket 2: Application Layer 24
Nonpersistent HTTP (cont.) time 5. HTTP client receives response message containing html file, displays html. Parsing html file, finds references to 10 jpeg objects 6. Steps 1-5 repeated for each of 10 jpeg objects 4. HTTP server closes TCP connection. 결과적으로총 11 번의 TCP connection 생성 By default, most browsers open 5 to 10 parallel connections 2: Application Layer 25
Non-Persistent HTTP: Response time Definition of RTT: time to send a small packet to travel from client to server and back. Response time: one RTT to initiate TCP connection one RTT for HTTP request and first few bytes of HTTP response to return file transmission time total = 2RTT+transmit time initiate TCP connection RTT request file RTT file received time Three-way handshake time Piggybacked ACK time to transmit file 2: Application Layer 26
Persistent HTTP Nonpersistent HTTP issues: requires 2 RTTs per object OS overhead for each TCP connection browsers often open parallel TCP connections to fetch referenced objects Persistent HTTP server leaves connection open after sending response 일정시간이후에 HTTP server 는연결을닫음 subsequent HTTP messages between same client/server sent over open connection Persistent without pipelining: client issues new request only when previous response has been received one RTT for each referenced object Persistent with pipelining: default in HTTP/1.1 client sends requests as soon as it encounters a referenced object Response 받기전에보냄 Back-to-back requests as little as one RTT for all the referenced objects 2: Application Layer 27
HTTP request message two types of HTTP messages: request, response HTTP request message: ASCII (human-readable format) request line (GET, POST, HEAD commands) header lines Carriage return, line feed indicates end of message GET /somedir/page.html HTTP/1.1 Host: www.someschool.edu User-agent: Mozilla/4.0 Connection: close Accept-language:fr (extra carriage return, line feed) 연결을유지하려면 Connection: Keep-Alive 브라우져는 Explorer, OS 는 Window 2000 서버 2: Application Layer 28
HTTP request message: general format 2: Application Layer 29
Uploading form input Post method: Web page often includes form input Input is uploaded to server in entity body 예 : search engine 의 search word URL method: Post의역할을 GET으로도실행가능 GET URL 형태의 URL 부분을변형해서가능 www.somesite.com/animalsearch?monkeys&banana 2: Application Layer 30
Method types HTTP/1.0 GET POST HEAD GET 과유사하나서버는이메시지를받을시요구된 object 를주지않음.( 응답은함 ) debugging 목적에사용 HTTP/1.1 GET, POST, HEAD PUT 웹서버의특정 path ( 폴더 ) 에 object 를 upload 할때 DELETE 웹서버의특정폴더의 object 를 delete 2: Application Layer 31
HTTP response message status line (protocol status code status phrase) data, e.g., requested HTML file header lines HTTP/1.1 200 OK Connection close 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... Object 가생성되거나가장최근에 modified 된시각표시 2: Application Layer 32
HTTP response status codes In first line in server->client response message. A few sample codes: 200 OK request succeeded, requested object later in this message 301 Moved Permanently requested object moved, new location specified later in this message (Location:) 400 Bad Request request message not understood by server 404 Not Found requested document not found on this server 505 HTTP Version Not Supported 2: Application Layer 33
Cookies HTTP 는 stateless 함 즉, 사용자가어떤페이지를가져갔는지등이서버에기록되지않음 Cookie 의목적 사용자의행위에대한것을서버가기록하여, 사용자가다음방문시사용자에게도움을주려고함 Stateless한 HTTP 상에서 Stateful 한성격을구현 2: Application Layer 34
Cookies Client 가 Server 에접속시 Server 가 Cookie 값을생성하여 client 에부여 Client 는이값을받아저장하고있다가다시동일 server 에접속시이값을제시 Server 는이값과함께 client 의행위를기록했다가 ( 예 : Amazon 의경우어떤종류의책들을보았는지등 ), client 가다음에접속시도움을줌 ( 예 : 동일분야의책추천등 ) 즉, Cookie 값은 server 가부여하되, 보관은 Server 와 client 양쪽에됨 2: Application Layer 35
Cookies: keeping state (cont.) client ebay 8734 cookie file ebay 8734 amazon 1678 one week later: ebay 8734 amazon 1678 usual http request msg usual http response Set-cookie: 1678 usual http request msg cookie: 1678 usual http response msg usual http request msg cookie: 1678 usual http response msg server Amazon server creates ID 1678 for user create entry cookiespecific action cookiespectific action access access backend database 2: Application Layer 36
Cookies (continued) What cookies can bring: authorization shopping carts recommendations Stateless 한 HTTP 위에서 session layer 생성 예 : Web-based e-mail How to keep state : protocol endpoints: maintain state at sender/receiver over multiple transactions cookies: http messages carry state aside Cookies and privacy: cookies permit sites to learn a lot about you you may supply name and e-mail to sites 2: Application Layer 37
Web caches (proxy server) Goal: 웹페이지를가져오는시간을단축하기위하여중간에 두는서버 user sets browser: Web accesses via cache browser sends all HTTP requests to cache object in cache: cache returns object else cache requests object from origin server, then returns object to client client client Proxy server origin server origin server 2: Application Layer 38
More about Web caching cache acts as both client and server typically cache is installed by ISP (university, company, residential ISP) Why Web caching? reduce response time for client request reduce 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 Layer 39
Caching example Assumptions average object size = 100,000 bits avg. request rate from institution s browsers to origin servers = 15/sec Internet delay: round trip delay in public internet = 2 sec Consequences utilization on LAN = 15% utilization on access link = 100% total delay = Internet delay + access delay + LAN delay = 2 sec + minutes + milliseconds institutional network public Internet 1.5 Mbps access link 10 Mbps LAN origin servers institutional cache 2: Application Layer 40
Caching example (cont) possible solution increase bandwidth of access link to, say, 10 Mbps consequence utilization on LAN = 15% utilization on access link = 15% Total delay = Internet delay + access delay + LAN delay = 2 sec + msecs + msecs often a costly upgrade institutional network public Internet 10 Mbps access link 10 Mbps LAN origin servers institutional cache 2: Application Layer 41
Caching example (cont) possible solution: install cache suppose hit rate is 0.4 consequence 40% requests will be satisfied almost immediately 60% requests satisfied by origin server utilization of access link reduced to 60%, resulting in negligible delays (say 10 msec) total avg delay = Internet delay + access delay + LAN delay=0.6*2secs+ 0.6*0.01secs +0.4*0.01secs 1.2 secs institutional network public Internet 1.5 Mbps access link 10 Mbps LAN origin servers institutional cache 2: Application Layer 42
Conditional GET Cache 가가진 object 가최신것인지 server 에게확인하는방법 Method 는 GET 인데 If-modified-Since: <date> 라인을사용 명시된시간이후에서버의 object 가변경되었다면변경된자료전송 변경이안되었다면 object 는응답필요없으므로 304 Not Modified 로만응답 일반적으로 browser 에 cache 기능이있음 그러나자신이가진 web page 가최신인지확신이안갈때 Server 로 Conditional GET request 전송 Client 와 Server 간에 Proxy Server 가있는경우, 서버의응답메시지에 Expires 시간값이있음 ( 예 : 30 초 ) Proxy server 가캐쉬한후이시간이지났을때는 Proxy server 는 Conditional GET 으로 server 에문의 Server 가 Conditional GET 을이해하지못할때는그냥일반적인 GET 으로인식하여해당페이지를무조건보내줌 2: Application Layer 43
Conditional GET cache: specify date of cached copy in HTTP request If-modified-since: <date> server: response contains no object if cached copy is upto-date: HTTP/1.0 304 Not Modified cache HTTP request msg If-modified-since: <date> HTTP response HTTP/1.0 304 Not Modified HTTP request msg If-modified-since: <date> HTTP response HTTP/1.0 200 OK <data> server object not modified object modified 2: Application Layer 44
Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2.9 Building a Web server 2: Application Layer 45
현재이이미지를표시할수없습니다. FTP: the file transfer protocol user at host FTP user interface FTP client local file system file transfer FTP server remote file system transfer file to/from remote host client/server model client: side that initiates transfer (either to/from remote) server: remote host ftp: RFC 959 ftp server: port 21 2: Application Layer 46
FTP: separate control, data connections FTP client contacts FTP server at port 21, specifying TCP as transport protocol Client obtains authorization over control connection Client browses remote directory by sending commands over control connection. When server receives file transfer command, server initiates & opens 2 nd TCP connection (data connection, server port # = 20) for file transfer to client After transferring one file, server closes data connection. FTP client TCP control connection to sever port 21 TCP data connection from server port 20 FTP server Server opens another TCP data connection to transfer another file Control connection은 FTP session이끝날때까지 open되어있음 [Active mode] Data connection은매 file transfer마다열리고닫힘 control connection: out of band 2: Application Layer 47
FTP commands, responses Sample commands: sent as ASCII text over control channel USER username PASS password LIST return list of file in current directory RETR filename retrieves (gets) file STOR filename stores (puts) file onto remote host Sample return codes status code and phrase (as in HTTP) 331 Username OK, password required 125 data connection already open; transfer starting 425 Can t open data connection 452 Error writing file 2: Application Layer 48
Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2: Application Layer 49
Electronic Mail Three major components: user agents mail servers simple mail transfer protocol: SMTP User Agent a.k.a. mail reader composing, editing, reading mail messages e.g., Eudora, Outlook, elm, Mozilla Thunderbird outgoing, incoming messages stored on server mail server SMTP mail server user agent user agent SMTP SMTP user agent outgoing message queue mail server user mailbox user agent user agent user agent 2: Application Layer 50
Electronic Mail: mail servers Mail Servers mailbox contains incoming messages for user message queue of outgoing (to be sent) mail messages 상대방 mail server 가고장나서 mail 메시지를전달하기어려울때보관했다가재시도 (30 분마다 ) SMTP protocol between mail servers to send email messages Mail server 는타 mail server 에메일을전달할때는 SMTP client 로동작하고, 타 mail server 로부터메일을수신할때는 SMTP server 로동작 mail server SMTP mail server user agent user agent SMTP SMTP user agent mail server user agent user agent user agent 2: Application Layer 51
Electronic Mail: SMTP [RFC 2821] uses TCP to reliably transfer email message from client to server, port 25 direct transfer: sending server to receiving server three phases of transfer handshaking (greeting) transfer of messages closure command/response interaction commands: ASCII text response: status code and phrase messages must be in 7-bit ASCII 2: Application Layer 52
Scenario: Alice sends message to Bob 1) Alice uses UA to compose message and to bob@someschool.edu 2) Alice s UA sends message to her mail server; message placed in message queue 3) Client side of SMTP opens TCP connection with Bob s mail server 4) SMTP client sends Alice s message over the TCP connection 5) Bob s mail server places the message in Bob s mailbox 6) Bob invokes his user agent to read message 1 user agent mail server 2 3 4 mail server 5 6 user agent 2: Application Layer 53
Sample SMTP interaction TCP connection 이맺어진후동작, S: SMTP server, C: SMTP client 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 실제메시지의시작을알리는 SMTP Command 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 여러개의메일을보낼시반복가능 Indicate end of a message ( 즉, CRLF.CRLF) 2: Application Layer 54
Try to interact with SMTP server using Telnet for yourself: Email client (reader) 를사용하지않고 Telnet 을사용하여 email 을보내는방법 telnet servername 25 (servername 은 local mail server 의 name) You will receive 220 reply from server enter HELO, MAIL FROM, RCPT TO, DATA, QUIT commands 2: Application Layer 55
SMTP: final words SMTP uses persistent connections ( 한개의 TCP 연결을연상태에서 pp.54 의붉은색 box 를반복. Client 는이들의 push 전송이다끝났을때비로소 QUIT 전송 ) SMTP server uses CRLF.CRLF to determine end of message Comparison with HTTP: HTTP: pull protocol User가 server에있는정보를 pull해오는방식 TCP 연결도 file을받으려는측이 initiate SMTP: push protocol Sending 메일서버가 rcv. 메일서버에게 push TCP 연결도 file을보내려는측이 initiate SMTP: 메시지 (header & body) 는모두 7-bit ASCII format이어야함 Image등의 binary 파일을포함하고있어도 7-bit ASCII 로 encoding해야함 HTTP: 위와같은제한이없음 HTTP: 한개의 response 메시지는한개의 object만포함 SMTP: 메시지에포함된모든 objects들은그메시지에포함되어전송 2: Application Layer 56
Mail message format( 실제메시지 부분 ) 실제메시지부분 (pp.54 의청색 box 부분 ) 을 header 와 body 로나누어구성할수있다 (header 부분에여러가지필요한정보를기입하기위함. Header 부분은 SMTP command 가아님.) RFC 822->2822->5322: Internet message format: header lines, e.g., body To: From: Subject: the message, ASCII characters only header body blank line 2: Application Layer 57
현재이이미지를표시할수없습니다. Mail access protocols Agent 와서버가다른머신에있는경우 Alice s agent SMTP SMTP (push 동작 ) Alice s mail server (push 동작 ) Bob s mail server SMTP: delivery/storage to receiver s server Mail access protocol: retrieval from server POP: 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 server HTTP: Hotmail, Yahoo! Mail, etc. Agent 와서버가다른머신에있는경우 access protocol (POP3, IMAP, HTTP) (pull 동작 ) Bob s agent 2: Application Layer 58
POP3 가장간단한 access 프로토콜 TCP 연결을맺은상태에서메일을 pull 해옴 download and delete mode. Bob cannot re-read e-mail from his different machine Download-and-keep : copies of messages for his different clients POP3 is stateless across sessions ( 구현이 simple) 서버에 Delete 한것만반영되고, directory 를만들거나하는작업은불가능 User 는자신의 PC 에메일을가져온후디렉토리를만들고메일들을정리해놓아도메일서버에는반영이안됨 복수의단말기에서메일을읽을시불편 2: Application Layer 59
POP3 예 (download & delete) authorization phase client commands: user: declare username pass: password server responses +OK -ERR transaction phase, client: list: list message numbers retr: retrieve message by number dele: delete quit S: +OK POP3 server ready C: user bob S: +OK C: pass hungry S: +OK user successfully logged on 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 2 contents> S:. C: dele 2 C: quit S: +OK POP3 server signing off Update phase 시작 ( 서버는메시지 1,2 를 mailbox 에서실제로제거함 ) 2: Application Layer 60
IMAP IMAP 은서버에서메일을관리하고단말로는메일메시지의헤더부분만기본적으로보내준다 단말에서해당메일제목을클릭시내용을 copy 해옴 복수개의단말에서메일을체크하는환경에편리 서버와단말간에자동씽크설정가능 서버에메일이들어오면단말로자동 push 됨 스마트폰등에서메일을체크시편리 안드로이드폰에서는 이메일 앱을사용하여다양한메일 (gmail, daum, naver 등 ) 들과 IMAP 씽크를설정하면해당메일계정으로새매일이수신되면자동으로알려줌 2: Application Layer 61
Web-based E-mail Hotmail in mid-1990 시작 User agent 는일반 web browser Bob 의 UA 는 HTTP 를이용하여 mail 서버의 mail box 를 access Alice 의 UA 도 HTTP 를이용하여 mail 서버에 mail 전달 Mail server 간의전달은여전히 SMTP 사용 2: Application Layer 62
Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2.9 Building a Web server 2: Application Layer 63
DNS: Domain Name System People: many identifiers: SSN, name, passport # Internet hosts, routers: IP address (32 bit) - used for addressing datagrams name, e.g., ww.yahoo.com - used by humans Q: map between IP addresses and name? Domain Name System: distributed database implemented in hierarchy of many name servers application-layer protocol host, routers, name servers to communicate to resolve names (address/name translation) note: core Internet function, implemented as application-layer protocol complexity at network s edge 2: Application Layer 64
DNS DNS services Hostname to IP address translation Host aliasing alias hostname으로부터 canonical hostname을얻음 Mail server aliasing Mail server의 alias hostname으로부터 canonical hostname을얻음 Load distribution Client가 web 서버의이름에대해 DNA query 했을때, 그서버가 replicated web 서버들인경우 DNS 서버는 entire set of IP addresses 를주게되는데, 이때주소의 ordering을매번 rotate해서준다 Canonical hostname 은복잡하므로 user 는단순한 alias hostname 을사용하는것이편리하나, 결국은 DNS query 를통해 canonical hostname 을얻어야함 Why not centralize DNS? single point of failure traffic volume distant centralized database maintenance doesn t scale! Replicated Web servers 는한개의 canonical hostname 에 set of IP addresses 가대응되어있음 2: Application Layer 65
Distributed, Hierarchical Database Root DNS Servers Top-level Domain servers com DNS servers org DNS servers edu DNS servers Authoritative Domain servers yahoo.com DNS servers amazon.com DNS servers pbs.org DNS servers poly.edu umass.edu DNS servers DNS servers Client wants IP for www.amazon.com; 1 st approx: Client queries a root DNS server to find com DNS server Client queries com DNS server to get amazon.com DNS server Client queries amazon.com DNS server to get IP address for www.amazon.com 2: Application Layer 66
DNS: Root name servers contacted by local name server that can not resolve name root name server: contacts authoritative name server if name mapping not known gets mapping returns mapping to local name server e NASA Mt View, CA f Internet Software C. Palo Alto, CA (and 36 other locations) b USC-ISI Marina del Rey, CA l ICANN Los Angeles, CA a Verisign, Dulles, VA c Cogent, Herndon, VA (also LA) d U Maryland College Park, MD g US DoD Vienna, VA h ARL Aberdeen, MD j Verisign, ( 21 locations) k RIPE London (also 16 other locations) i Autonomica, Stockholm (plus 28 other locations) m WIDE Tokyo (also Seoul, Paris, SF) 13 root name servers worldwide ( 국내 : f,j,m,l 의복제서버운용. 전세계 :300 가넘는복제서버운용됨 ) 2: Application Layer 67
TLD and Authoritative Servers Top-level domain (TLD) servers: responsible for com, org, net, edu, etc, and all top-level country domains uk, fr, ca, jp. Verisign maintains servers for.com &.net TLD Educause for.edu TLD Authoritative DNS servers: 각기관은 publicly accessible server (e.g., Web 서버, mail 서버등 ) 의 hostname to IP mappings 을제공할필요가있다 기관자체로 authoritative DNS 서버를가지던가, ISP 에의뢰하여해결 2: Application Layer 68
Local Name Server Does not strictly belong to hierarchy Each ISP (residential ISP, company, academic department, university) has one. Also called default name server When a host makes a DNS query, query is sent to its local DNS server Acts as a proxy, forwards query into hierarchy. 2: Application Layer 69
Example iterative query (query 의답이바로옴 ) root DNS server Host at cis.poly.edu wants IP address for gaia.cs.umass.edu 이그림의형태가일반적인형태 iterated query: contacted server replies with name of server to contact I don t know this name, but ask this server Recursive query (query 가또 query 를발생시킴 ) local DNS server dns.poly.edu 1 2 8 requesting host cis.poly.edu 3 4 5 7 TLD DNS server 6 edu authoritative DNS server dns.umass.edu gaia.cs.umass.edu 2: Application Layer 70
DNS name resolution example root DNS server recursive query: 2 3 puts burden of name resolution on contacted name server 7 6 TLD DNS server heavy load? local DNS server dns.poly.edu 5 4 1 8 requesting host cis.poly.edu authoritative DNS server dns.cs.umass.edu gaia.cs.umass.edu 2: Application Layer 71
DNS: caching and updating records once (any) name server learns mapping, it caches mapping cache entries timeout (disappear) after some time TLD servers typically cached in local name servers Thus root name servers not often visited update/notify mechanisms under design by IETF RFC 2136 http://www.ietf.org/html.charters/dnsind-charter.html 2: Application Layer 72
DNS records DNS: distributed db storing resource records (RR) RR format: (name, value, type, ttl) Type=A name is hostname value is IP address Type=NS 해당도메인의 authoritative DNS 서버의이름을알려줌 name is domain (e.g. foo.com) value is hostname of authoritative DNS server for this domain Type=CNAME name is alias name for some canonical (the real) name www.ibm.com is really servereast.backup2.ibm.com value is canonical name Type=MX value is name of mail server associated with name 2: Application Layer 73
DNS protocol, messages DNS protocol : query and reply messages, both with same message format msg header identification: 16 bit # for query, reply to query uses same # flags: query or reply recursion desired recursion available reply is authoritative 2: Application Layer 74
DNS protocol, messages Name, type fields for a query RRs in response to query records for authoritative servers additional helpful info that may be used 2: Application Layer 75
Inserting records into DNS ( 예 ) Network Utopia 라는신규기업창업시서버등록과정 Domain name networkuptopia.com 을 registrar (e.g., Network Solutions: 2000년에 $21B에 Verisign에인수됨 ) 에등록 도메인네임을등록해주는서비스를 Naming 서비스 라칭함 신규기업은자신을위한 authoritative DNS server (primary and secondary의 2개 ) 의이름과 IP 주소를 registrar에제공 dns1.networkutopia.com, dns2.networkutopia.com Registrar는 TLD com 서버에이두 DNS 서버를위한 type NS record와 type A record들을등록 ( 예 ) dns1.networkutopia.com을위한 RRs (networkutopia.com, dns1.networkutopia.com, NS) (dns1.networkutopia.com, 212.212.212.1, A) 추가로회사의 Web server (www.networkuptopia.com) 를위한 Type A record와 mail server (mail.networkutopia.com) 를위한 Type MX record 를위두개의 authoritative DNS server 에등록필요 2: Application Layer 76
Chapter 2: Application layer 2.1 Principles of network applications app architectures app requirements 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2: Application Layer 77
Pure P2P architecture no always-on server arbitrary end systems directly communicate peers are intermittently connected and change IP addresses peer-peer Three topics: File distribution Searching for information Case Study: Skype 2: Application Layer 78
P2P: centralized directory original Napster design 1 when peer connects, it informs central server: centralized directory server 1 Bob peers IP address 1 2 content Alice queries for Hey Jude 2 1 1 3 3 Alice requests file from Bob & file is transferred to Alice Alice 2: Application Layer 79
P2P: problems with centralized directory Single point of failure Performance bottleneck Copyright infringement file transfer is decentralized, but locating content is highly centralized 2: Application Layer 80
Query flooding: Gnutella fully distributed 구조 no central server public domain protocol Gnutellar 를위한 overlay network 상에서 file 을찾기위한 query 를 flood 방식으로전달하고, file 을가진 host 를찾으면그호스트로직접 TCP 연결을생성하여 file 을얻는다. edge between peer X and Y if there s a TCP connection all active peers and edges is overlay net Edge is not a physical link Given peer will typically be connected with < 10 overlay neighbors 2: Application Layer 81
Gnutella: protocol Query message sent over existing TCP connections peers flood Query message QueryHit sent over reverse path, using preexisting TCP connections limited scope flooding ( 과도한 flood traffic을방지하기위해 forward되는홉수를제한함 ) Scalability 문제발생 Query QueryHit File transfer: HTTP Query QueryHit 2: Application Layer 82
Exploiting heterogeneity: KaZaA Napster (central directory server 사용 ) 와 Gnutellar (fully distributed 구조 ) 의 idea 를조합 Proprietary protocol Encrypt all control data Data 는 encrypt 하지않음 구조 : 전체구조는 Gnutella 와유사하나, 특정노드들을 group leader 로지정하여, 이것들이자신이관장하는작은영역에서는 napster 에서의 directory server 와유사한역할을하도록함 2: Application Layer 83
KaZaA: group leader Group leader 는 children 노드들의 IP 주소와 children 노드가 sharing 하는모든 file 의 identifier 를저장하는 database 를유지 한 group leader 가수백개의 children 노드관리 Group leader 끼리는서로간에 TCP 로연결하여, group leader 간 overlay network 구성 Group leader 는 dedicated 서버가아니라일반 peer ordinary peer group-leader peer neighoring relationships in overlay network 2: Application Layer 84
File Distribution: Server-Client vs P2P Question : How much time to distribute file from one server to N peers? File, size F Server u 1 d 1 u 2 u d 2 s u s : server upload bandwidth u i : peer i upload bandwidth d i : peer i download bandwidth d N u N Network (with abundant bandwidth) 2: Application Layer 85
File distribution time: server-client 서버는 a file 을 N peer 에게 sequential 하게전송해야함 A file 을 distribute 하는데걸리는시간은최소한 NF/u s time client i takes F/d i time to download 최소다운로드 rate 를가진 peer 는 F/min(d i ) 시간내에 a file 을받을수없음 최소분배시간은최소 F/min(d i ) F Server d N u N u u 2 1 d 1 u d s 2 Network (with abundant bandwidth) Time to distribute F to N clients using client/server approach = d cs = max { NF/u s, F/min(d i ) } i increases linearly in N (for large N) 2: Application Layer 86
File distribution time: P2P Server 초기에는서버만 file 을가지고있으므로서버는최소한번은전송을해야함 : F/u s time F u u 2 1 d 1 u d s 2 client i takes F/d i time to download (c-s 경우와동일 ) N peer 에 F bits 이전달되어야하므로총 NF bits 이네트웍으로전달 (upload) 되어야함 d N u N Network (with abundant bandwidth) Total upload capacity 는 u s + Σu i 최소분배시간은 NF/(u s + Σu i ) d P2P = max { F/u s, F/min(d i ), NF/(u s + Σu i ) } i 2: Application Layer 87
Server-client vs. P2P: example Client upload rate = u, F/u = 1 hour, u s = 10u, d min u s 3.5 Minimum Distribution Time 3 2.5 2 1.5 1 0.5 P2P Client-Server N(=peer 갯수 ) 이커져도 1 hour 이내 scalability 0 0 5 10 15 20 25 30 35 N 2: Application Layer 88
File distribution: BitTorrent P2P file distribution tracker: node tracking peers participating in a torrent torrent: 어느특정파일의분배에참여하는모든 peer 의집합 Equal-size chunk 들을교환 obtain list of peers trading chunks peer 2: Application Layer 89
BitTorrent (1) file divided into 256KB chunks. Torrent 에 join 하는절차 ( 예 : Alice): Alice registers with tracker Tracker 는참여하고있는 peer 중일부 ( 50 개 ) 를랜덤하게선택하여이 peer 들의 IP 주소를 Alice 에게알려줌 Alice 는이 peer 들에 TCP 연결시도 연결성공되는 peer 를 neighboring peer 라함 while downloading, peer uploads chunks to other peers peers may come and go once peer has entire file, it may (selfishly) leave or (altruistically) remain 2: Application Layer 90
BitTorrent (2) Pulling Chunks at any given time, different peers have different subsets of file chunks periodically, a peer (Alice) asks each neighbor for list of chunks that they have. Alice sends requests for her missing chunks rarest first Chunks를전송하는방법 : titfor-tat (equal retaliation) Chunk를가장많이공급해주는이웃에게 chunk를보내줌 Alice sends chunks to 4 neighbors currently sending her chunks at the highest rate re-evaluate top 4 every 10 secs 이 4 peer는 unchoked라불림 every 30 secs: randomly select additional neighbor, starts sending chunks optimistically unchoked라불림 newly chosen peer may join top 4 이 5개 peer외에는 Alice로부터 chunk를못받음 (choked) 2: Application Layer 91
BitTorrent: Tit-for-tat (1) Alice 가 Bob 을 optimistically unchoked 로선택해서전송을하면 (2) Alice 는 Bob 의 top 4 provider 중하나가될가능성이높다 (3) 그러면 Bob 도 Alice 로전송을하게되므로 Bob 도 Alice 의 top-four provider 중하나가될가능성이높다 With higher upload rate, can find better trading partners & get file faster! 2: Application Layer 92
Distributed Hash Table (DHT) Tracker 가없는 p-to-p 시스템에사용 DHT = distributed P2P database over a large number of peers (possibly millions) Database has (key, value) pairs; ( 예 1) key: ss number; value: human name (156-45-7081, Jonny Wu) ( 예 2) key: content type; value: IP address (e.g., names of movies, albums, software, 203.17.123.38) Peers query DB with key DB returns values that match the key Peers can also insert (key, value) peers
DHT Identifiers Assign an integer identifier to each peer in range [0,2 n -1]. Each identifier can be represented by n bits. Require each key to be an integer in same range. 문자열로된원래키로부터정수키값을얻기위해 hash function을사용 eg, key = h( Led Zeppelin IV ) Hash function 은모든 peer 에게공개되어있음 This is why they call it a distributed hash table
How to assign keys to peers? (key, value) pair 를어느 peer 에저장할것인가? 의이슈 해결책 : key 값에가장가까운 (closest) identifier 값을가지는 peer 에해당 (key,value) pair 를저장 편의상 closest 를 immediate successor of key( 가장가까운큰값 ) 로사용하자 ( 예 )n=4 면 key 와 identifier 는 [0,15] 범위의값 8 개의 peer 를가정 : 1,3,4,5,8,10,12,14 key = 13, then successor peer = 14, key = 15, then successor peer = 1 (11, Johnny Wu) 는 peer 12 에저장 중앙서버가없는구조에서키에가장가까운 peer 의 identifier 값이얼마이고그 peer 의 IP 주소를어떻게알아낼것인가? Circular DHT Peer 마다 key 값이가까운몇개의 peer 를기록한 routing table 사용
Circular DHT (1) 1 15 3 4 12 5 10 8 Each peer only aware of immediate successor and predecessor. Overlay network
Circle DHT (2) 1111 Response: I am 0001 0011 1110 Query: Who s resp for key 1110? 1110 Query: Who s resp for key 1110? 0100 1100 1110 1110 1110 0101 1010 1110 1000 문제점 : 오래걸림 N/2 messages on avg to resolve query, when there are N peers
Circular DHT with Shortcuts Each peer keeps track of IP addresses of predecessor, successor, shortcut peers. 15 12 10 Query 를 key 에가장가까운 successor 나 shortcut peer 에전송 위의예에서는 key 가 13 이므로 successor(4) 보다는 shortcut(8) 에보냄 Reduced from 6 to 2 messages. Possible to design shortcuts so O(log N) neighbors, O(log N) messages in query 8 1 3 5 4 Who s resp for key 1110?
Peer Churn (peer 가 circular DHT 에서나가고새로들어올때인식하는방법 ) 15 12 10 8 1 3 5 4 To 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. Peer 5 abruptly leaves Peer 4 detects; makes 8 its immediate successor; asks 8 who its immediate successor is; makes 8 s immediate successor 10 its second successor. What if peer 13 wants to join?
P2P Case study: Skype FastTrack, Kazza의고안자가시작, 2005년에 ebay가 $2.6B에인수, 2011년에 Microsoft가 $8.5B에인수 proprietary application-layer protocol (inferred via reverse engineering) 패킷은모두암호화되어전송 hierarchical overlay with SN(Supernode) & 일반노드 Index maps Skype usernames to IP addresses 이 index 는 SN 들에분산되어저장 ( 확실치않지만 DHT 의형태로추정됨 ) Skype login server Skype clients (SC) Supernode (SN) 2: Application Layer 100
Peers as relays Problem when both Alice and Bob are behind NATs. NAT prevents an outside peer from initiating a call to insider peer NAT 뒤에있는사용자는걸려오는전화를받을수없다 Solution: Using Alice s and Bob s SNs, Relay is chosen Each peer initiates session with relay. Peers can now communicate through NATs via relay 2: Application Layer 101
Relay 를이용하여통화하는예 When Alice want to call Bob Alice 와 Bob 은각각 NAT 뒤에있다고가정 Alice 를관장하는 SN 을 A, Bob 를관장하는 SN 을 B 라하자 Alice 는 A 에알림 A 는 B 에알림 B 는 Bob 에 Alice 가발신통화하려는의도를알림 A,B 는제 3 의 non-nated SN 을선정 ( 이것이 relay R) A 는 Alice 에, B 는 Bob 에게각각 R 로호세션을시작하도록지시 Alice 는 Alice-to-R 연결을통해 R 로음성패킷전송 이패킷은 R-to-Bob 연결 (B 에의해시작된연결 ) 을통해 Bob 으로전달 Bob 이 Alice 에게보내는음성패킷은반대로전송 2: Application Layer 102
Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P applications 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2: Application Layer 103
Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm two types of transport service via socket API: unreliable datagram reliable, byte streamoriented socket a host-local, application-created, OS-controlled interface (a door ) into which application process can both send and receive messages to/from another application process 2: Application Layer 104
Socket-programming using TCP Socket: a door between application process and endend-transport protocol (UCP or TCP) TCP service: reliable transfer of bytes from one process to another controlled by application developer controlled by operating system process socket TCP with buffers, variables internet process socket TCP with buffers, variables controlled by application developer controlled by operating system host or server host or server 2: Application Layer 105
Socket programming with TCP Client must contact server server process must first be running server must have created socket (door) that welcomes client s contact Client contacts server by: creating client-local TCP socket specifying IP address, port number of server process When 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 client allows server to talk with multiple clients source port numbers used to distinguish clients (more in Chap 3) application viewpoint TCP provides reliable, in-order transfer of bytes ( pipe ) between client and server 2: Application Layer 106
Client/server socket interaction: TCP Client program create a socket TCP in client initiate 3-way handshake During handshake, Client process knocks on welcoming door (welcomesocket) of server process When server hears the knocking on welcoming door, it create a new door ( 즉, new socket) (connection socket) dedicated to this client by invoking welcomesocket s accept( ) method At the end of handshaking, a TCP connection exists between the client s socket & server s new socket welcomesocket is free to listen for requests from other clients Direct virtual pipe 2: Application Layer 107
Client/server socket interaction: TCP Server (running on hostid) create socket, port=x, for incoming request: welcomesocket = ServerSocket() wait for incoming connection request connectionsocket = welcomesocket.accept() read request from connectionsocket write reply to connectionsocket close connectionsocket TCP connection setup Client create socket, connect to hostid, port=x clientsocket = Socket() send request using clientsocket read reply from clientsocket close clientsocket 2: Application Layer 108
Stream jargon A 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. Client Process process input stream output stream keyboard infromuser outtoserver monitor infromserver client TCP clientsocket socket input stream TCP socket to network from network 2: Application Layer 109
Socket programming with TCP Example client-server app: 1) client reads line from standard input (infromuser stream), sends to server via socket (outtoserver stream) 2) server reads line from socket 3) server converts line to uppercase, sends back to client 4) client reads (infromserver stream), prints modified line from socket on standard output (monitor) 2: Application Layer 110
Example: Java client (TCP) BufferedReader 타입의 infromuser 라는 stream object 생성, 이 stream 을 System.in (standard input) 으로초기화하여키보드로부터읽을수있게함 Create input stream Create client socket, connect to server (initiate TCP connection) Create output stream attached to socket import java.io.*; import java.net.*; class TCPClient { Socket type 의 clientsocket 을생성하고서버에 TCP connection 을맺기위한 contact 를 initiate 함. 서버를 contact 하므로서버 name 과 port number 필요. 서버 name 으로부터 IP 주소를얻기위해 DNS lookup 이 implicit 하게발생됨 public static void main(string argv[]) throws Exception { String sentence; String modifiedsentence; Server name BufferedReader infromuser = new BufferedReader(new InputStreamReader(System.in)); Socket clientsocket = new Socket("hostname", 6789); Server port number DataOutputStream outtoserver = new DataOutputStream(clientSocket.getOutputStream()); 소켓에 attach 된 stream object 생성. outtoserver 는소켓으로내보내는프로세스제공 2: Application Layer 111
Example: Java client (TCP), cont. 소켓에 attach 된 stream object 생성. infromserver 는소켓에서부터들어오는프로세스제공 Create input stream attached to socket User 가 type 한 line 을 string 타입인 sentence 에저장 (CR 을칠때까지 ) Send line to server Read line from server 서버에서들어온 character 가 stream infromserver 를거쳐 string 타입인 ModifiedSentence 에저장 } } 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(); 서버가보낸 modifiedsentence 를모니터에표시 String 타입인 sentence 에 CR 을붙여 outtoserver 스트림으로보냄 2: Application Layer 112
Example: Java server (TCP) Create a new socket, called connectionsocket (also has same port number 6789), when some client knocks on welcomesocket. 이제 TCP가연결되어 client의 clientsocket과서버의 connectionsocket간 direct virtual pipe 형성 welcomesocket is free to listen for requests from other clients Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket 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) { Object welcomesocket 생성 (ServerSocket 타입임 ). welcomesocket 은 client 가두드리는것을기다리는 door 와같음. welcomesocket listens on port number 6789 Socket connectionsocket = welcomesocket.accept(); BufferedReader infromclient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); 2: Application Layer 113
Example: Java server (TCP), cont Create output stream, attached to socket Read in line from socket DataOutputStream outtoclient = new DataOutputStream(connectionSocket.getOutputStream()); clientsentence = infromclient.readline(); Write out line to socket Takes the line sent by the client, captalize it, add a CR } using a method touppercase( ) } } capitalizedsentence = clientsentence.touppercase() + '\n'; outtoclient.writebytes(capitalizedsentence); End of while loop, loop back and wait for another client connection 2: Application Layer 114
Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS 2.6 P2P file sharing 2.7 Socket programming with TCP 2.8 Socket programming with UDP 2.9 Building a Web server 2: Application Layer 115
소켓생성 in TCP & UDP TCP 에서는 client socket 이생성되면이소켓이바로 server 에컨택을함 컨택한다는뜻은 TCP handshaking 시작을의미 서버에서는컨택이오면이에대응되는새로운한개의소켓생성 (a connection socket) 즉, 매 TCP 연결마다새로운 client 소켓에대응되는새로운소켓이서버에생성됨 서버의응용프로그램하나가 client 에서접속이올때마다소켓을생성하므로다수의소켓을생성하게됨. 즉, 동일한포트번호 ( 예 : 웹서버의경우 80) 를가진복수개의소켓이서버에존재함. 따라서서버에소켓을생성시킨 client 의소켓까지같이지칭해야한개의 TCP 소켓이지정됨 --> 4 tuple 이필요 2: Application Layer 116
소켓생성 in TCP & UDP UDP 에서는 client socket 이생성되어도서버에컨택을하지않음. 따라서 client 소켓생성에따라서버에새로운소켓이생성되지않음. 응용프로그램하나에서버소켓하나로모든 client 의세그먼트송수신 포트번호한개에는단한개의소켓이서버에존재함 서버소켓으로만한개의 UDP 소켓이지정됨 2 tuple 필요 Connection 을맺지않으므로, Client 에서서버의 IP 주소와포트번호를적은 datagram 을 explicitly 하게만들어주어야함. 2: Application Layer 117
Socket programming with UDP UDP: no connection between client and server no handshaking no need for welcoming socket ( 소켓은단한개만있으면됨 ) no virtual pipe ( 즉, no streams attached to socket) Sender는데이터를보낼때 stream으로보낼수없으므로, 목적지의 IP주소와 port번호가적힌패킷단위로보내야함 Server는매수신패킷마다 sender의 IP address와 port번호를추출해야함 UDP: transmitted data may be received out of order, or lost application viewpoint UDP provides unreliable transfer of groups of bytes ( datagrams ) between client and server 2: Application Layer 118
Client/server socket interaction: UDP Server (running on hostid) Client create socket, port=x, for incoming request: serversocket = DatagramSocket() read request from serversocket create socket, clientsocket = DatagramSocket() Create, address (hostid, port=x, send datagram request using clientsocket write reply to serversocket specifying client host address, port number read reply from clientsocket close clientsocket 2: Application Layer 119
Example: Java client (UDP) keyboard monitor Output: sends packet (recall that TCP sent byte stream ) Client Process process input stream UDP packet infromuser sendpacket receivepacket client UDP clientsocket socket UDP packet UDP socket Input: receives packet (recall thattcp received byte stream ) to network from network 2: Application Layer 120
Socket programming with UDP Example client-server app: 1) client reads line from standard input, sends to server via socket 2) server reads a line from socket 3) server converts line to uppercase, sends the modified line out its socket back to client 4) client reads, prints modified line from socket on standard output (monitor) 2: Application Layer 121
Example: Java client (UDP) Create input stream Create client socket Translate hostname to IP address using DNS 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]; DatagramSocket type 의 clientsocket 생성. 하지만 server 로 connection 을생성하지않으므로 server 를 contact 하지않는다. 따라서서버의 name 이나 port 번호가필요없음. Client 소켓의 port 번호는자동생성 method getbyname( ) 은서버 name 을받아서 IP 주소를 return (by DNS lookup) 구해진 IP 주소를 InetAddress type 의 IPAddress object 에넣음 Array of bytes 인 senddata 와 receivedata 는각각 client 가보내고받을데이터를저장 String sentence = infromuser.readline(); senddata = sentence.getbytes(); Type conversion 수행. String type인 sentence를받아서 array of bytes 형태인 senddata로 rename 2: Application Layer 122