2 Chapter 2 Application Layer 1 Web and

  • Slides: 124
Download presentation
2장 애플리케이션(응용) 계층 Chapter 2: Application Layer 1

2장 애플리케이션(응용) 계층 Chapter 2: Application Layer 1

Web and HTTP First some jargon r Web page consists of objects r Object

Web and HTTP First some jargon r Web page consists of objects r Object can be HTML file, JPEG image, Java applet, audio file, … r Web page consists of base HTML-file which includes several referenced objects r Each object is addressable by a URL r Example URL: www. someschool. edu/some. Dept/pic. gif host name path name Chapter 2: Application Layer 20

HTTP overview HTTP: hypertext transfer protocol r Web’s application layer protocol r client/server model

HTTP overview HTTP: hypertext transfer protocol r Web’s application layer protocol r client/server model m client: browser that requests, receives, “displays” Web objects m server: Web server sends objects in response to requests r HTTP 1. 0: RFC 1945 r HTTP 1. 1: RFC 2068 HT TP req ues PC running HT t TP res Explorer pon se st ue q e r P nse Server T o p running HT es r P T Apache Web HT server Mac running Navigator Chapter 2: Application Layer 21

HTTP overview (continued) Uses TCP: r client initiates TCP connection (creates socket) to server,

HTTP overview (continued) Uses TCP: r client initiates TCP connection (creates socket) to server, port 80 r server accepts TCP connection from client r HTTP messages (applicationlayer protocol messages) exchanged between browser (HTTP client) and Web server (HTTP server) r TCP connection closed HTTP is “stateless” r server maintains no information about past client requests aside Protocols that maintain “state” are complex! r past history (state) must be maintained r if server/client crashes, their views of “state” may be inconsistent, must be reconciled Chapter 2: Application Layer 22

HTTP connections Nonpersistent HTTP r At most one object is sent over a TCP

HTTP connections Nonpersistent HTTP r At most one object is sent over a TCP connection. r HTTP/1. 0 uses nonpersistent HTTP Persistent HTTP r Multiple objects can be sent over single TCP connection between client and server. r HTTP/1. 1 uses persistent connections in default mode Chapter 2: Application Layer 23

Nonpersistent HTTP (contains text, Suppose user enters URL references to 10 www. some. School.

Nonpersistent HTTP (contains text, Suppose user enters URL references to 10 www. some. School. edu/some. Department/home. index jpeg images) 1 a. HTTP client initiates TCP connection to HTTP server (process) at www. some. School. edu on port 80 2. HTTP client sends HTTP request message (containing URL) into TCP connection socket. Message indicates that client wants object some. Department/home. index 1 b. HTTP server at host www. some. School. 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 time Chapter 2: Application Layer 24

Nonpersistent HTTP (cont. ) 4. HTTP server closes TCP 5. HTTP client receives response

Nonpersistent HTTP (cont. ) 4. HTTP server closes TCP 5. HTTP client receives response connection. message containing html file, displays html. Parsing html file, finds 10 referenced jpeg objects time 6. Steps 1 -5 repeated for each of 10 jpeg objects Chapter 2: Application Layer 25

Response time modeling Definition of RRT: time to send a small packet to travel

Response time modeling Definition of RRT: time to send a small packet to travel from client to server and back. Response time: r one RTT to initiate TCP connection r one RTT for HTTP request and first few bytes of HTTP response to return r file transmission time total = 2 RTT+transmit time initiate TCP connection RTT request file RTT file received time to transmit file time Chapter 2: Application Layer 26

Persistent HTTP Nonpersistent HTTP issues: r requires 2 RTTs per object r OS must

Persistent HTTP Nonpersistent HTTP issues: r requires 2 RTTs per object r OS must work and allocate host resources for each TCP connection r but browsers often open parallel TCP connections to fetch referenced objects Persistent HTTP r server leaves connection open after sending response r subsequent HTTP messages between same client/server are sent over connection Persistent without pipelining: r client issues new request only when previous response has been received r one RTT for each referenced object Persistent with pipelining: r default in HTTP/1. 1 r client sends requests as soon as it encounters a referenced object r as little as one RTT for all the referenced objects Chapter 2: Application Layer 27

HTTP request message r two types of HTTP messages: request, response r HTTP request

HTTP request message r two types of HTTP messages: request, response r HTTP request message: m ASCII (human-readable format) request line (GET, POST, HEAD commands) GET /somedir/page. html HTTP/1. 1 Host: www. someschool. edu User-agent: Mozilla/4. 0 header Connection: close lines Accept-language: fr Carriage return, line feed indicates end of message (extra carriage return, line feed) Chapter 2: Application Layer 28

HTTP request message: general format Chapter 2: Application Layer 29

HTTP request message: general format Chapter 2: Application Layer 29

Uploading form input Post method: r Web page often includes form input r Input

Uploading form input Post method: r Web page often includes form input r Input is uploaded to server in entity body URL method: r Uses GET method r Input is uploaded in URL field of request line: www. somesite. com/animalsearch? monkeys&banana Chapter 2: Application Layer 30

Method types HTTP/1. 0 r GET r POST r HEAD m asks server to

Method types HTTP/1. 0 r GET r POST r HEAD m asks server to leave requested object out of response HTTP/1. 1 r GET, POST, HEAD r PUT m uploads file in entity body to path specified in URL field r DELETE m deletes file specified in the URL field Chapter 2: Application Layer 31

HTTP response message status line (protocol status code status phrase) header lines data, e.

HTTP response message status line (protocol status code status phrase) header lines data, e. g. , requested HTML file 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. . . Chapter 2: Application Layer 32

HTTP response status codes In first line in server->client response message. A few sample

HTTP response status codes In first line in server->client response message. A few sample codes: 200 OK m request succeeded, requested object later in this message 301 Moved Permanently m requested object moved, new location specified later in this message (Location: ) 400 Bad Request m request message not understood by server 404 Not Found m requested document not found on this server 505 HTTP Version Not Supported Chapter 2: Application Layer 33

Trying out HTTP (client side) for yourself 1. Telnet to your favorite Web server:

Trying out HTTP (client side) for yourself 1. Telnet to your favorite Web server: telnet cis. poly. edu 80 Opens TCP connection to port 80 (default HTTP server port) at cis. poly. edu. Anything typed in sent to port 80 at cis. poly. edu 2. Type in a GET HTTP request: GET /~ross/ HTTP/1. 1 Host: cis. poly. edu By typing this in (hit carriage return twice), you send this minimal (but complete) GET request to HTTP server 3. Look at response message sent by HTTP server! Chapter 2: Application Layer 34

User-server state: cookies Many major Web sites use cookies Four components: 1) cookie header

User-server state: cookies Many major Web sites use cookies Four components: 1) cookie header line in the HTTP response message 2) cookie header line in HTTP request message 3) cookie file kept on user’s host and managed by user’s browser 4) back-end database at Web site Example: m m m Susan access Internet always from same PC She visits a specific ecommerce site for first time When initial HTTP requests arrives at site, site creates a unique ID and creates an entry in backend database for ID Chapter 2: Application Layer 35

Cookies: keeping “state” (cont. ) client ebay: 8734 Cookie file amazon: 1678 ebay: 8734

Cookies: keeping “state” (cont. ) client ebay: 8734 Cookie file amazon: 1678 ebay: 8734 usual http request msg usual http response + Set-cookie: 1678 usual http request msg cookie: 1678 usual http response msg Cookie file amazon: 1678 ebay: 8734 cookiespecific action ss acce ac ce one week later: e n server da try i tab n b creates ID as ac e ke nd 1678 for user ss Cookie file server usual http request msg cookie: 1678 usual http response msg cookiespectific action Chapter 2: Application Layer 36

Cookies (continued) What cookies can bring: r authorization r shopping carts r recommendations r

Cookies (continued) What cookies can bring: r authorization r shopping carts r recommendations r user session state (Web e-mail) aside Cookies and privacy: r cookies permit sites to learn a lot about you r you may supply name and e-mail to sites r search engines use redirection & cookies to learn yet more r advertising companies obtain info across sites Chapter 2: Application Layer 37

Web caches (proxy server) Goal: satisfy client request without involving origin server r user

Web caches (proxy server) Goal: satisfy client request without involving origin server r user sets browser: Web accesses via cache r browser sends all HTTP requests to cache m m object in cache: cache returns object else cache requests object from origin server, then returns object to client origin server HT client. HTTP TP req Proxy server ues t res pon se t s ue q re P nse o T p HT es r TP T H client est u q e Pr T nse o p HT res P T HT origin server Chapter 2: Application Layer 38

More about Web caching r Cache acts as both client and server r Typically

More about Web caching r Cache acts as both client and server r Typically cache is installed by ISP (university, company, residential ISP) Why Web caching? r Reduce response time for client request. r Reduce traffic on an institution’s access link. r Internet dense with caches enables “poor” content providers to effectively deliver content (but so does P 2 P file sharing) Chapter 2: Application Layer 39

Caching example Assumptions r average object size = 100, 000 bits r avg. request

Caching example Assumptions r average object size = 100, 000 bits r avg. request rate from institution’s browsers to origin servers = 15/sec r delay from institutional router to any origin server and back to router = 2 sec Consequences origin servers public Internet 1. 5 Mbps access link institutional network 10 Mbps LAN r utilization on LAN = 15% r utilization on access link = 100% r total delay = Internet delay + access delay + LAN delay = 2 sec + minutes + milliseconds institutional cache Chapter 2: Application Layer 40

Caching example (cont) Possible solution r increase bandwidth of access link to, say, 10

Caching example (cont) Possible solution r increase bandwidth of access link to, say, 10 Mbps Consequences origin servers public Internet r utilization on LAN = 15% r utilization on access link = 15% = Internet delay + access delay + LAN delay = 2 sec + msecs r often a costly upgrade 10 Mbps access link r Total delay institutional network 10 Mbps LAN institutional cache Chapter 2: Application Layer 41

Caching example (cont) origin servers Install cache r suppose hit rate is. 4 Consequence

Caching example (cont) origin servers Install cache r suppose hit rate is. 4 Consequence public Internet r 40% requests will be satisfied almost immediately r 60% requests satisfied by origin server r utilization of access link reduced to 60%, resulting in negligible delays (say 10 msec) r total avg delay = Internet delay + access delay + LAN delay =. 6*(2. 01) secs + milliseconds < 1. 4 secs 1. 5 Mbps access link institutional network 10 Mbps LAN institutional cache Chapter 2: Application Layer 42

Conditional GET r Goal: don’t send object if cache has up-to-date cached version r

Conditional GET r Goal: don’t send object if cache has up-to-date cached version r cache: specify date of cached copy in HTTP request If-modified-since: <date> r server: response contains no object if cached copy is up-to -date: HTTP/1. 0 304 Not Modified server cache HTTP request msg If-modified-since: <date> HTTP response object not modified HTTP/1. 0 304 Not Modified HTTP request msg If-modified-since: <date> HTTP response object modified HTTP/1. 0 200 OK <data> Chapter 2: Application Layer 43

2. 3. 1 FTP 명령과 응답 명령 예: r 제어 채널상으로 ASCII 텍 r

2. 3. 1 FTP 명령과 응답 명령 예: r 제어 채널상으로 ASCII 텍 r r r 스트로써 보낸다. 4개의 ASCII 대문자 USER username PASS password LIST 현재 디렉토리내의 파일 리스트를 보내진다. RETR filename 파일을 추출한다. (get) r STOR filename 원격 호 스트에 파일을 저장한다. 응답 코드의 예 r 상태코드와 문구 (HTTP 같음) r 3 숫자와 옵션 메시지 r 331 Username OK, password required r 125 data connection already open; transfer starting r 425 Can’t open data connection r 452 Error writing file (put) Chapter 2: Application Layer 47

SMTP 상호동작 예 S: C: S: C: C: C: S: 220 hamburger. edu HELO

SMTP 상호동작 예 S: C: S: C: C: C: S: 220 hamburger. edu HELO crepes. fr 250 Hello crepes. fr, pleased to meet you MAIL FROM: <[email protected] fr> 250 [email protected] fr. . . Sender ok RCPT TO: <[email protected] edu> 250 [email protected] edu. . . Recipient ok DATA 354 Enter mail, end with ". " on a line by itself Do you like ketchup? How about pickles? . 250 Message accepted for delivery QUIT 221 hamburger. edu closing connection Chapter 2: Application Layer 53

비-ASCII 데이터를 위한 MIME 확장 r MIME: multimedia mail extension, RFC 2045, 2056 r

비-ASCII 데이터를 위한 MIME 확장 r MIME: multimedia mail extension, RFC 2045, 2056 r 메시지 헤더에 추가헤더로 MIME 내용 타입 선언 MIME 버전 데이터 인코드에 사용된 방법 멀티미디어 데이터 타입, 서브타입, 매개변수 선언 인코드된 데이타 From: [email protected] fr To: [email protected] edu Subject: Picture of yummy crepe. MIME-Version: 1. 0 Content-Transfer-Encoding: base 64 Content-Type: image/jpeg base 64 encoded data. . . . . base 64 encoded data Chapter 2: Application Layer 57

수신된 메시지 r 수신 서버는 헤더라인을 추가 Received: from crepes. fr by hamburger. edu;

수신된 메시지 r 수신 서버는 헤더라인을 추가 Received: from crepes. fr by hamburger. edu; 12 Oct 98 15: 27: 39 GMT From: [email protected] fr To: [email protected] edu Subject: Picture of yummy crepe. MIME-Version: 1. 0 Content-Transfer-Encoding: base 64 Content-Type: image/jpeg base 64 encoded data. . . . . base 64 encoded data Chapter 2: Application Layer 58

POP 3 프로토콜(1) TCP 포트 110 인증 단계 r 클라이언트 명령: m m user:

POP 3 프로토콜(1) TCP 포트 110 인증 단계 r 클라이언트 명령: m m user: <사용자이름> pass: <비밀번호> r 서버 응답 m m +OK: 바로 앞 명령이 OK -ERR: 바로 앞 명령 오류 트랜잭션 단계, client: r list: 메시지 번호와 각 크기 r retr: 번호에 의해 가져옴 r dele: 삭제 r quit S: C: S: +OK POP 3 server ready user bob +OK pass hungry +OK user successfully logged C: S: S: S: C: C: S: list 1 498 2 912. retr 1 <message 1 contents>. dele 1 retr 2 <message 1 contents>. dele 2 quit +OK POP 3 server signing off Chapter 2: Application Layer 60 on

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2

Chapter 2: Application layer r 2. 1 Principles of network applications r 2. 2 Web and HTTP r 2. 3 FTP r 2. 4 Electronic Mail m SMTP, POP 3, IMAP r 2. 5 DNS r 2. 6 P 2 P file sharing r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP r 2. 9 Building a Web server Chapter 2: Application Layer 64

DNS: Domain Name System People: many identifiers: m SSN, name, passport # Internet hosts,

DNS: Domain Name System People: many identifiers: m SSN, name, passport # Internet hosts, routers: m m 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: r distributed database implemented in hierarchy of many name servers r application-layer protocol host, routers, name servers to communicate to resolve names (address/name translation) m note: core Internet function, implemented as application-layer protocol m complexity at network’s “edge” Chapter 2: Application Layer 65

DNS services r Hostname to IP address translation r Host aliasing m Canonical and

DNS services r Hostname to IP address translation r Host aliasing m Canonical and alias names r Mail server aliasing r Load distribution m Replicated Web servers: set of IP addresses for one canonical name Why not centralize DNS? r single point of failure r traffic volume r distant centralized database r maintenance doesn’t scale! Chapter 2: Application Layer 66

Distributed, Hierarchical Database Root DNS Servers com DNS servers yahoo. com amazon. com DNS

Distributed, Hierarchical Database Root DNS Servers com DNS servers yahoo. com amazon. com DNS servers org DNS servers pbs. org DNS servers edu DNS servers poly. edu umass. edu DNS servers Client wants IP for www. amazon. com; 1 st approx: r Client queries a root server to find com DNS server r Client queries com DNS server to get amazon. com DNS server r Client queries amazon. com DNS server to get IP address for www. amazon. com Chapter 2: Application Layer 67

DNS: Root name servers r contacted by local name server that can not resolve

DNS: Root name servers r contacted by local name server that can not resolve name r root name server: m m m contacts authoritative name server if name mapping not known gets mapping returns mapping to local name server a Verisign, Dulles, VA c Cogent, Herndon, VA (also Los Angeles) d U Maryland College Park, MD k RIPE London (also Amsterdam, g US Do. D Vienna, VA Frankfurt) Stockholm (plus 3 i Autonomica, h ARL Aberdeen, MD other locations) j Verisign, ( 11 locations) m WIDE Tokyo e NASA Mt View, CA f Internet Software C. Palo Alto, CA (and 17 other locations) 13 root name servers worldwide b USC-ISI Marina del Rey, CA l ICANN Los Angeles, CA Chapter 2: Application Layer 68

TLD and Authoritative Servers r Top-level domain (TLD) servers: responsible for com, org, net,

TLD and Authoritative Servers r Top-level domain (TLD) servers: responsible for com, org, net, edu, etc, and all top-level country domains uk, fr, ca, jp. m Network solutions maintains servers for com TLD m Educause for edu TLD r Authoritative DNS servers: organization’s DNS servers, providing authoritative hostname to IP mappings for organization’s servers (e. g. , Web and mail). m Can be maintained by organization or service provider Chapter 2: Application Layer 69

Local Name Server r Does not strictly belong to hierarchy r Each ISP (residential

Local Name Server r Does not strictly belong to hierarchy r Each ISP (residential ISP, company, university) has one. m Also called “default name server” r When a host makes a DNS query, query is sent to its local DNS server m Acts as a proxy, forwards query into hierarchy. Chapter 2: Application Layer 70

Example root DNS server 2 r Host at cis. poly. edu 3 wants IP

Example root DNS server 2 r Host at cis. poly. edu 3 wants IP address for gaia. cs. umass. edu 4 TLD DNS server 5 local DNS server dns. poly. edu 1 7 8 requesting host 6 authoritative DNS server dns. cs. umass. edu cis. poly. edu gaia. cs. umass. edu Chapter 2: Application Layer 71

Recursive queries recursive query: 2 r puts burden of name resolution on contacted name

Recursive queries recursive query: 2 r puts burden of name resolution on contacted name server r heavy load? iterated query: r contacted server root DNS server 3 7 local DNS server dns. poly. edu 1 6 TLD DNS server 5 4 8 replies with name of server to contact r “I don’t know this requesting host name, but ask this cis. poly. edu server” authoritative DNS server dns. cs. umass. edu gaia. cs. umass. edu Chapter 2: Application Layer 72

DNS: caching and updating records r once (any) name server learns mapping, it caches

DNS: caching and updating records r once (any) name server learns mapping, it caches mapping m cache entries timeout (disappear) after some time m TLD servers typically cached in local name servers • Thus root name servers not often visited r update/notify mechanisms under design by IETF m RFC 2136 m http: //www. ietf. org/html. charters/dnsind-charter. html Chapter 2: Application Layer 73

DNS records DNS: distributed db storing resource records (RR) RR format: (name, value, type,

DNS records DNS: distributed db storing resource records (RR) RR format: (name, value, type, ttl) r Type=A m name is hostname m value is IP address r Type=CNAME m name is alias name for some “cannonical” (the real) name www. ibm. com is really r Type=NS servereast. backup 2. ibm. com m name is domain (e. g. m value is cannonical name foo. com) m value is IP address of r Type=MX authoritative name server m value is name of mailserver for this domain associated with name Chapter 2: Application Layer 74

DNS protocol, messages DNS protocol : query and reply messages, both with same message

DNS protocol, messages DNS protocol : query and reply messages, both with same message format msg header r identification: 16 bit # for query, reply to query uses same # r flags: m query or reply m recursion desired m recursion available m reply is authoritative Chapter 2: Application Layer 75

DNS protocol, messages Name, type fields for a query RRs in reponse to query

DNS protocol, messages Name, type fields for a query RRs in reponse to query records for authoritative servers additional “helpful” info that may be used Chapter 2: Application Layer 76

Inserting records into DNS r Example: just created startup “Network Utopia” r Register name

Inserting records into DNS r Example: just created startup “Network Utopia” r Register name networkuptopia. com at a registrar (e. g. , Network Solutions) m m Need to provide registrar with names and IP addresses of your authoritative name server (primary and secondary) Registrar inserts two RRs into the com TLD server: (networkutopia. com, dns 1. networkutopia. com, NS) (dns 1. networkutopia. com, 212. 1, A) r Put in authoritative server Type A record for www. networkuptopia. com and Type MX record for networkutopia. com r How do people get the IP address of your Web site? Chapter 2: Application Layer 77

Chapter 2: Application layer r 2. 1 Principles of network applications m m app

Chapter 2: Application layer r 2. 1 Principles of network applications m m app architectures app requirements r 2. 2 Web and HTTP r 2. 4 Electronic Mail m SMTP, POP 3, IMAP r 2. 5 DNS r 2. 6 P 2 P file sharing r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP r 2. 9 Building a Web server Chapter 2: Application Layer 78

P 2 P file sharing Example r Alice runs P 2 P client application

P 2 P file sharing Example r Alice runs P 2 P client application on her notebook computer r Intermittently connects to Internet; gets new IP address for each connection r Asks for “Hey Jude” r Application displays other peers that have copy of Hey Jude. r Alice chooses one of the peers, Bob. r File is copied from Bob’s PC to Alice’s notebook: HTTP r While Alice downloads, other users uploading from Alice. r Alice’s peer is both a Web client and a transient Web server. All peers are servers = highly scalable! Chapter 2: Application Layer 79

P 2 P: centralized directory original “Napster” design 1) when peer connects, it informs

P 2 P: centralized directory original “Napster” design 1) when peer connects, it informs central server: m m Bob centralized directory server 1 peers IP address content 2) Alice queries for “Hey Jude” 3) Alice requests file from Bob 1 3 1 2 1 Alice Chapter 2: Application Layer 80

P 2 P: problems with centralized directory r Single point of failure r Performance

P 2 P: problems with centralized directory r Single point of failure r Performance bottleneck r Copyright infringement file transfer is decentralized, but locating content is highly decentralized Chapter 2: Application Layer 81

Query flooding: Gnutella r fully distributed m no central server r public domain protocol

Query flooding: Gnutella r fully distributed m no central server r public domain protocol r many Gnutella clients implementing protocol overlay network: graph r edge between peer X and Y if there’s a TCP connection r all active peers and edges is overlay net r Edge is not a physical link r Given peer will typically be connected with < 10 overlay neighbors Chapter 2: Application Layer 82

Gnutella: protocol r Query message sent over existing TCP connections r peers forward Query

Gnutella: protocol r Query message sent over existing TCP connections r peers forward Query message ry e r Query. Hit it Qu H ry sent over e Qu reverse Query path File transfer: HTTP Query. Hit Qu ery Query. Hit Scalability: limited scope flooding Qu er y Chapter 2: Application Layer 83

Gnutella: Peer joining Joining peer X must find some other peer in Gnutella network:

Gnutella: Peer joining Joining peer X must find some other peer in Gnutella network: use list of candidate peers 2. X sequentially attempts to make TCP with peers on list until connection setup with Y 3. X sends Ping message to Y; Y forwards Ping message. 4. All peers receiving Ping message respond with Pong message 5. X receives many Pong messages. It can then setup additional TCP connections Peer leaving: see homework problem! 1. Chapter 2: Application Layer 84

Exploiting heterogeneity: Ka. Za. A r Each peer is either a group leader or

Exploiting heterogeneity: Ka. Za. A r Each peer is either a group leader or assigned to a group leader. m m TCP connection between peer and its group leader. TCP connections between some pairs of group leaders. r Group leader tracks the content in all its children. Chapter 2: Application Layer 85

Ka. Za. A: Querying r Each file has a hash and a descriptor r

Ka. Za. A: Querying r Each file has a hash and a descriptor r Client sends keyword query to its group leader r Group leader responds with matches: m For each match: metadata, hash, IP address r If group leader forwards query to other group leaders, they respond with matches r Client then selects files for downloading m HTTP requests using hash as identifier sent to peers holding desired file Chapter 2: Application Layer 86

Kazaa tricks r Limitations on simultaneous uploads r Request queuing r Incentive priorities r

Kazaa tricks r Limitations on simultaneous uploads r Request queuing r Incentive priorities r Parallel downloading Chapter 2: Application Layer 87

소켓 함수(1) r 소켓생성 s = socket(pf, type, protocol) pf = 프로토콜 패밀리 PF_INET,

소켓 함수(1) r 소켓생성 s = socket(pf, type, protocol) pf = 프로토콜 패밀리 PF_INET, PF_PUP, PF_APPLETAlk, PF_UNIX type = 트랜스포트연결의 서비스종류 SOCK_STREAM, SOCK_DGRAM protocol = 트랜스포트 프로토콜 IPPROTO_TCP, IPPROTO_UDP r 소켓종료 close(s) Chapter 2: Application Layer 94

소켓 함수(2) r 지역주소 지정 bind(s, localaddr, addrlen) r 목적지 주소로 연결 struct sockaddr_in

소켓 함수(2) r 지역주소 지정 bind(s, localaddr, addrlen) r 목적지 주소로 연결 struct sockaddr_in { unsigned short sin_family; unsigned short sin_port; struct in_addr sin_addr; char sin_zero[8]; // 사용안함 connect(s, destaddr, addrlen) r message에 있는 메시지 전송 } send(s, message, length, flags) r 메시지를 buffer에 저장 recv(s, buffer, length, flags) IP주소 포트번호 Chapter 2: Application Layer 95

클라이언트/서버 소켓 상호동작: TCP 서버 클라이언트 소켓 생성 s = socket(pf, type, protocol) bind(s,

클라이언트/서버 소켓 상호동작: TCP 서버 클라이언트 소켓 생성 s = socket(pf, type, protocol) bind(s, lad, adln) listen(s, qln) ns = accept(s, adln) 연결요청 기다림 소켓 생성 s = socket(pf, type, protocol) ( bind(s, lad, adln) ) 연결 요청 TCP 연결 설정 connect(s, dad, adln) send(s, msg, ln, f) recv(ns, buf, ln, f) send(ns, msg, ln, f) recv(s, buf, ln, f) Chapter 2: Application Layer 97

클라이언트/서버 소켓 상호동작: TCP 응용 서버 응용 프로세스 s 버퍼 buf 프로세스 ns ladr

클라이언트/서버 소켓 상호동작: TCP 응용 서버 응용 프로세스 s 버퍼 buf 프로세스 ns ladr A lpt a radr rpt 1 응용(클라이언트) 버퍼 s ladr A lpt a radr B rpt b lpt=a msg ladr B b lpt radr A rpt a 포트번호 1 TCP 2 lpt=b TCP IP(ladr=A) B, b, A, a IP(ladr=B) NIF TCP연결요청 A, a, B, b TCP연결수락 NIF Chapter 2: Application Layer 98

클라이언트/서버 소켓 상호동작: TCP 응용 서버 응용 프로세스 s 버퍼 buf 프로세스 ns ladr

클라이언트/서버 소켓 상호동작: TCP 응용 서버 응용 프로세스 s 버퍼 buf 프로세스 ns ladr A lpt a radr rpt 1 응용(클라이언트) 버퍼 ladr A lpt a radr B rpt b lpt=a 일치 TCP s ladr B b lpt radr A rpt a 복사 포트번호 1 포트번호 A, a, B, b 2 복사 lpt=b TCP IP(ladr=A) NIF msg A, a, B, b IP(ladr=B) A, a, B, b, A, a NIF TCP연결 Chapter 2: Application Layer 99

Struct in_addr { unsigned long s_addr; } 클라이언트 예(1/3) struct sockaddr_in { unsigned short

Struct in_addr { unsigned long s_addr; } 클라이언트 예(1/3) struct sockaddr_in { unsigned short sin_family; unsigned short sin_port; struct in_addr sin_addr; char sin_zero[8]; //사용안함 } Serv. Addr msg Protocol family Port IP 주소 . . . #include <stdio. h> #include <sys/socket. h> #include <arpa/inet. h> #include <stdlib. h> #include <string. h> #include <unistd. h> int main(void) { int sock; struct sockaddr_in Serv. Addr; char msg[100]; unsigned int msg. Str. Len; int bytes. Sent=0; Chapter 2: Application Layer 100

클라이언트 예(2/3) msg host to network a b c /0 gets(msg); //assign the server

클라이언트 예(2/3) msg host to network a b c /0 gets(msg); //assign the server address infomation memset(&Serv. Addr, 0, sizeof(Serv. Addr)); Serv. Addr. sin_family=AF_INET; Serv. Addr. sin_port=htons(9876); Serv. Addr. sin_addr. s_addr=inet_addr("211. 207"); 21110=110100112 = 1 x 27+1 x 26+1 x 24+1 x 21+1 x 20 Serv. Addr AF_NET 9876 11010011 11001111 Chapter 2: Application Layer 101

클라이언트 예(3/3) //socket creation sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); //connetc to server connect(sock, (struct

클라이언트 예(3/3) //socket creation sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); //connetc to server connect(sock, (struct sockaddr *) &Serv. Addr, sizeof(struct sockaddr_in)); //send data msg. Str. Len=strlen(msg); for(; ; ){ bytes. Sent=send(sock, msg. Str. Len, 0); printf("bytes. Sent : %d n", bytes. Sent); //scanf("%s", msg); gets(msg); msg. Str. Len=strlen(msg); } close(sock); exit(0); } Chapter 2: Application Layer 102

서버 예(1/2) #include <stdio. h> Serv. Addr. sin_family=AF_INET; #include <sys/socket. h> //Serv. Addr. sin_addr.

서버 예(1/2) #include <stdio. h> Serv. Addr. sin_family=AF_INET; #include <sys/socket. h> //Serv. Addr. sin_addr. s_addr=htol(INADDR_ANY); #include <arpa/inet. h> Serv. Addr. sin_addr. s_addr=inet_addr("211. 207"); #include <stdlib. h> Serv. Addr. sin_port=htons(9876); #include <string. h> //server socket creation #include <unistd. h> s. Sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); int main(void) { //bind int s. Sock; bind(s. Sock, int c. Sock; (struct sockaddr *)&Serv. Addr, sizeof(struct sockaddr_in)); struct sockaddr_in Serv. Addr; struct sockaddr_in clnt. Addr; //listen unsigned int clnt. Len; listen(s. Sock, 5); char Rcv. Buffer[100]; int i=0, bytes. Rcvd; memset(&Serv. Addr, 0, sizeof(Serv. Addr)); Chapter 2: Application Layer 103

서버 예(2/2) //accpet clnt. Len = sizeof(struct sockaddr_in); c. Sock = accept(s. Sock, (struct

서버 예(2/2) //accpet clnt. Len = sizeof(struct sockaddr_in); c. Sock = accept(s. Sock, (struct sockaddr *)&clnt. Addr, &clnt. Len ); printf("ip : %sn", inet_ntoa(clnt. Addr. sin_addr)); bytes. Rcvd=recv(c. Sock, Rcv. Buffer, sizeof(Rcv. Buffer), 0); while(bytes. Rcvd > 0){ //receive printf("bytes. Rcvd 1: %d n", bytes. Rcvd); Rcv. Buffer[bytes. Rcvd]=''; printf("received string 1: %sn", Rcv. Buffer); //printf("start for %dn", bytes. Rcvd); bytes. Rcvd=0; printf("bytes. Rcvd 2: %d n", bytes. Rcvd); bytes. Rcvd=recv(c. Sock, Rcv. Buffer, sizeof(Rcv. Buffer), 0); printf("bytes. Rcvd 3: %d n", bytes. Rcvd); Rcv. Buffer[bytes. Rcvd]=''; printf("received string 3: %sn", Rcv. Buffer); //bytes. Rcvd=0; printf("end for %dn", bytes. Rcvd); // i++; } close(c. Sock); exit(0); } Chapter 2: Application Layer 104

Socket programming with TCP Example client-server app: 1) client reads line from standard input

Socket programming with TCP Example client-server app: 1) client reads line from standard input (in. From. User stream) , sends to server via socket (out. To. Server stream) 2) server reads line from socket 3) server converts line to uppercase, sends back to client 4) client reads, prints modified line from socket (in. From. Server stream) Client process client TCP socket Chapter 2: Application Layer 105

Example: Java client (TCP) import java. io. *; import java. net. *; class TCPClient

Example: Java client (TCP) import java. io. *; import java. net. *; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modified. Sentence; Create input stream Create client socket, connect to server Create output stream attached to socket Buffered. Reader in. From. User = new Buffered. Reader(new Input. Stream. Reader(System. in)); Socket client. Socket = new Socket("hostname", 6789); Data. Output. Stream out. To. Server = new Data. Output. Stream(client. Socket. get. Output. Stream()); Chapter 2: Application Layer 106

Example: Java client (TCP), cont. Create input stream attached to socket Buffered. Reader in.

Example: Java client (TCP), cont. Create input stream attached to socket Buffered. Reader in. From. Server = new Buffered. Reader(new Input. Stream. Reader(client. Socket. get. Input. Stream())); sentence = in. From. User. read. Line(); Send line to server out. To. Server. write. Bytes(sentence + 'n'); Read line from server modified. Sentence = in. From. Server. read. Line(); System. out. println("FROM SERVER: " + modified. Sentence); client. Socket. close(); } } Chapter 2: Application Layer 107

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

Example: Java server (TCP) import java. io. *; import java. net. *; class TCPServer { Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket public static void main(String argv[]) throws Exception { String client. Sentence; String capitalized. Sentence; Server. Socket welcome. Socket = new Server. Socket(6789); while(true) { Socket connection. Socket = welcome. Socket. accept(); Buffered. Reader in. From. Client = new Buffered. Reader(new Input. Stream. Reader(connection. Socket. get. Input. Stream())); Chapter 2: Application Layer 108

Example: Java server (TCP), cont Create output stream, attached to socket Data. Output. Stream

Example: Java server (TCP), cont Create output stream, attached to socket Data. Output. Stream out. To. Client = new Data. Output. Stream(connection. Socket. get. Output. Stream()); Read in line from socket client. Sentence = in. From. Client. read. Line(); capitalized. Sentence = client. Sentence. to. Upper. Case() + 'n'; Write out line to socket out. To. Client. write. Bytes(capitalized. Sentence); } } } End of while loop, loop back and wait for another client connection Chapter 2: Application Layer 109

소켓함수 r 송신 sendto(s, message, length, flags, destaddr, addrlen) r 수신 rcvfrom(s, buffer, length,

소켓함수 r 송신 sendto(s, message, length, flags, destaddr, addrlen) r 수신 rcvfrom(s, buffer, length, flags, fromaddr, addrlen) struct sockaddr_in { unsigned short sin_family; unsigned short sin_port; struct in_addr sin_addr; char sin_zero[8]; // 사용안함 } 포트번호 IP주소 Chapter 2: Application Layer 112

클라이언트/서버 소켓 상호동작: UDP 서버 클라이언트 소켓 생성 s = socket(pf, type, protocol) bind(s,

클라이언트/서버 소켓 상호동작: UDP 서버 클라이언트 소켓 생성 s = socket(pf, type, protocol) bind(s, lad, adln) recvfrom(s, buf, ln, f, fad, adln) bind(s, lad, adln) 데이터(요구) sendto(s, msg, ln, f, ad, adln) 데이터(응답) recvfrom(s, buf, ln, f, fad, adln) Chapter 2: Application Layer 113

클라이언트/서버 소켓 상호동작: UDP 응용 서버 응용 프로세스 B buf b s 응용(클라이언트) 버퍼

클라이언트/서버 소켓 상호동작: UDP 응용 서버 응용 프로세스 B buf b s 응용(클라이언트) 버퍼 버퍼 프로세스 s ladr A lpt a 1 ladr B lpt b 복사 일치 radr rpt lpt=a UDP 포트번호 A, a, B, b radr A rpt a 포트번호 1 2 복사 lpt=b UDP IP(ladr=A) NIF msg B, b, A, a IP(ladr=B) UDP A, a, B, b NIF Chapter 2: Application Layer 114

Client/server socket interaction: UDP Server (running on hostid) create socket, port=x, for incoming request:

Client/server socket interaction: UDP Server (running on hostid) create socket, port=x, for incoming request: server. Socket = Datagram. Socket() read request from server. Socket write reply to server. Socket specifying client host address, port number Client create socket, client. Socket = Datagram. Socket() Create, address (hostid, port=x, send datagram request using client. Socket read reply from client. Socket close client. Socket Chapter 2: Application Layer 115

Example: Java client (UDP) Client process Input: receives packet (TCP received “byte stream”) Output:

Example: Java client (UDP) Client process Input: receives packet (TCP received “byte stream”) Output: sends packet (TCP sent “byte stream”) client UDP socket Chapter 2: Application Layer 116

Example: Java client (UDP) import java. io. *; import java. net. *; Create input

Example: Java client (UDP) import java. io. *; import java. net. *; Create input stream Create client socket Translate hostname to IP address using DNS class UDPClient { public static void main(String args[]) throws Exception { Buffered. Reader in. From. User = new Buffered. Reader(new Input. Stream. Reader(System. in)); Datagram. Socket client. Socket = new Datagram. Socket(); Inet. Address IPAddress = Inet. Address. get. By. Name("hostname"); byte[] send. Data = new byte[1024]; byte[] receive. Data = new byte[1024]; String sentence = in. From. User. read. Line(); send. Data = sentence. get. Bytes(); Chapter 2: Application Layer 117

Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port Send

Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port Send datagram to server Datagram. Packet send. Packet = new Datagram. Packet(send. Data, send. Data. length, IPAddress, 9876); client. Socket. send(send. Packet); Datagram. Packet receive. Packet = new Datagram. Packet(receive. Data, receive. Data. length); Read datagram from server client. Socket. receive(receive. Packet); String modified. Sentence = new String(receive. Packet. get. Data()); System. out. println("FROM SERVER: " + modified. Sentence); client. Socket. close(); } } Chapter 2: Application Layer 118

Example: Java server (UDP) import java. io. *; import java. net. *; Create datagram

Example: Java server (UDP) import java. io. *; import java. net. *; Create datagram socket at port 9876 class UDPServer { public static void main(String args[]) throws Exception { Datagram. Socket server. Socket = new Datagram. Socket(9876); byte[] receive. Data = new byte[1024]; byte[] send. Data = new byte[1024]; while(true) { Create space for received datagram Receive datagram Datagram. Packet receive. Packet = new Datagram. Packet(receive. Data, receive. Data. length); server. Socket. receive(receive. Packet); Chapter 2: Application Layer 119

Example: Java server (UDP), cont String sentence = new String(receive. Packet. get. Data()); Get

Example: Java server (UDP), cont String sentence = new String(receive. Packet. get. Data()); Get IP addr port #, of sender Inet. Address IPAddress = receive. Packet. get. Address(); int port = receive. Packet. get. Port(); String capitalized. Sentence = sentence. to. Upper. Case(); send. Data = capitalized. Sentence. get. Bytes(); Create datagram to send to client Write out datagram to socket } Datagram. Packet send. Packet = new Datagram. Packet(send. Data, send. Data. length, IPAddress, port); server. Socket. send(send. Packet); } } End of while loop, loop back and wait for another datagram Chapter 2: Application Layer 120

Chapter 2: Application layer r 2. 1 Principles of network applications m m app

Chapter 2: Application layer r 2. 1 Principles of network applications m m app architectures app requirements r 2. 2 Web and HTTP r 2. 4 Electronic Mail m SMTP, POP 3, IMAP r 2. 5 DNS r 2. 6 P 2 P file sharing r 2. 7 Socket programming with TCP r 2. 8 Socket programming with UDP r 2. 9 Building a Web server Chapter 2: Application Layer 121

Building a simple Web server r handles one HTTP r r request accepts the

Building a simple Web server r handles one HTTP r r request accepts the request parses header obtains requested file from server’s file system creates HTTP response message: m r after creating server, you can request file using a browser (eg IE explorer) r see text for details header lines + file r sends response to client Chapter 2: Application Layer 122

Chapter 2: Summary Our study of network apps now complete! r Application architectures m

Chapter 2: Summary Our study of network apps now complete! r Application architectures m client-server m P 2 P m hybrid r application service requirements: m r specific protocols: m HTTP m FTP m SMTP, POP, IMAP m DNS r socket programming reliability, bandwidth, delay r Internet transport service model m m connection-oriented, reliable: TCP unreliable, datagrams: UDP Chapter 2: Application Layer 123

Chapter 2: Summary Most importantly: learned about protocols r typical request/reply message exchange: m

Chapter 2: Summary Most importantly: learned about protocols r typical request/reply message exchange: m m client requests info or service server responds with data, status code r message formats: m headers: fields giving info about data m data: info being communicated r control vs. data msgs in-band, out-of-band centralized vs. decentralized stateless vs. stateful reliable vs. unreliable msg transfer “complexity at network edge” m r r Chapter 2: Application Layer 124