3rd Edition: Chapter 2 - Laguna of Cakel :: 이곳은

Download Report

Transcript 3rd Edition: Chapter 2 - Laguna of Cakel :: 이곳은

2장
애플리케이션(응용) 계층
Chapter 2: Application Layer
1
2장: 애플리케이션 계층
 2.1 애플리케이션 계층 프로토콜의 원리
 2.2 웹과 HTTP
 2.3 파일전송; FTP
 2.4 인터넷 전자메일
 SMTP, POP3, IMAP
 2.5 DNS- 인터넷 디렉터리 서비스
 2.6 P2P 파일공유
 2.7 TCP 소켓 프로그래밍
 2.8 UDP 소켓 프로그래밍
 2.9 간단한 웹 서버 구축하기
Chapter 2: Application Layer
2
2장: 애플리케이션 계층
“네트워크 응용은
컴퓨터 네트워크의
존재의 이유”
 잘 알려지 응용계층
프로토콜을 고찰


목표:
 네트워크 애플리케이션의
개념과 구현 측면을 공부
 응용 계층 프로토콜
 트랜스포트 계층
서비스 모델
 클라이언트-서버
파라딤
 피어-피어 파라딤
 프로세스


HTTP
FTP
SMTP / POP3 / IMAP
DNS
 네트워크 응용 프로그래밍

소켓 API
Chapter 2: Application Layer
3
2장: 애플리케이션 계층
 2.1 애플리케이션 계층 프로토콜의 원리
 2.2 웹과 HTTP
 2.3 파일전송; FTP
 2.4 인터넷 전자메일
 SMTP, POP3, IMAP
 2.5 DNS- 인터넷 디렉터리 서비스
 2.6 P2P 파일공유
 2.7 TCP 소켓 프로그래밍
 2.8 UDP 소켓 프로그래밍
 2.9 간단한 웹 서버 구축하기
Chapter 2: Application Layer
4
인기있는 네트워크 응용
네트워크 애플리케이션은
다른 종단 시스템에서 동작
 여러 사용자 네트워크

 전자메일
 웹

 인스턴트 메시징

 원격 로그인

게임
스티리밍 저장된 비데오
클립
인터넷 전화
실시간 화상회의
병렬 전산처리
 P2P 파일공유
Chapter 2: Application Layer
5
네트워크 응용 개발
프로그램 작성은



상이한 종단 시스템에서
동작
네트워크상에서 통신
예., 웹: 웹 서버
소프트웨어는 브라우저
소프트웨어와 통신
코어 네트워크 장비를 위한
프로그램이 아님


코어 네트워크 장비는
응용계층에서 동작 하는
것이 아님
용이한 응용 개발을 허용
application
transport
network
data link
physical
application
transport
network
data link
physical
application
transport
network
data link
physical
Chapter 2: Application Layer
6
2.1.1 네트워크 애플리케이션 구조
“애플리케이션(응용) 계층 프로토콜은 네트워크
애플리케이션(응용)의 한 요소”
 클라이언트-서버
 피어-to-피어 (P2P)
 클라이언트-서버와 P2P의 혼합
Chapter 2: Application Layer
7
클라이언트-서버 구조
서버:




항상 켜있음
고정 IP 주소
서버끼리는 통신 않음
확장성을 위해 서버
집단(farm)
클라이언트:




서버와 통신
일시적으로 연결
동적 IP주소
클라이언트끼리 통신 않음
Chapter 2: Application Layer
8
순수 P2P 구조
 항상 켜놓은 서버 없음
 임의 종단 시스템간 통신
 피어들은 임시적으로
연결되고 IP주소도
변경도 됨
 예: 그누텔라(Gnutella)
 파일위치를 찾기위하여
질의하며 질의에
응답하고 질의를 전달
확장성 -각자가 서버기능
그러나 관리에 어려움
Chapter 2: Application Layer
9
클라이언트-서버와 P2P의 혼합
넵스터(Napster)
파일전송 P2P
 중앙집권된 파일 검색:

• 피어들은 중앙 서버에 내용물들을 등록
• 피어들은 내용물들의 위치를 중앙 서버에 질의
인스턴트 메시징
두 사용자간의 대화는 P2P
 존재 검색/위치확인은 중앙집권화:

• 사용자들은 접속시 중앙 서버에 자신의 IP 등록
• 사용자는 대화상대의 IP주소를 찾기 위하여 중앙서버에
접속
Chapter 2: Application Layer
10
2.1.2 프로세스간 통신
프로세스: 호스트에서
돌아가는 프로그램.
 같은 호스트 안에서는, 두
프로세스들은 OS에서
정의된 inter-process
communication 를 이용해
통신.
 다른 호스트간의
프로세스는 메시지교환을
통해 통신
클라이언트 프로세스:
통신을 야기하는
프로세스
서버 프로세스: 접속되기를
기다리는 프로세스
 주: P2P 구조를 갖는
응용들도 클라이언트
프로세스와 서버
프로세스를 갖는다.
Chapter 2: Application Layer
11
소켓
 프로세스는 자신의 소켓을
통해 메시지를 보내고
받는다.
 소켓을 문에 비유


송신 프로세스는 메시지를
문 밖으로 밀어 낸다.
이 송신 프로세스는 수신
프로세스의 문으로 메시지를
보내기 위해 문 뒤편의
트랜스포트 구조에 의존한다.
호스트 또는
서버
호스트 또는
서버
응용 개발자에
의해 제어
프로세스
프로세스
소켓
소켓
버퍼, 변수
등의 TCP
Internet
버퍼, 변수
등의 TCP
OS에 의해
제어
 API: (1) 트랜스포트 프로토콜 선택; (2) 매개변수의
설정(최대버퍼, 최대 세그먼트 크기 등)
Chapter 2: Application Layer
12
프로세스 주소체계
 한 프로세스가 메시지를
수신하기 위하여,
식별자를 가져야 한다.
 각 호스트는 32 비트
IP주소를 갖는다.
 질문: 프로세스가
동작하는 호스트의 IP
주소는 그 프로세스를
식별하는데 충분한가?
 답: 아니다, 많은
프로세스가 같은
호스트에서 돌아가기
때문이다.
 식별자라는 것은
호스트가 접속된 IP
주소와 그 호스트상의
프로세스를 나타내는
포트번호(port
numbers) 둘 다를
의미한다.
 포트번호의 예:


HTTP 서버: 80
메일 서버: 25
 후에 자세히 배운다.
Chapter 2: Application Layer
13
2.1.3 응용계층 프로토콜
메시지를 보내는 방법 정의
프로토콜은 다음의 내용을 정의
 교환되는 메시지 타입, 예, 요구 와 응답 메시지
 메시지 타입 문법: 메시지에 무슨 필드가 있고 필드간 구별
 필드의 의미, 즉, 필드 정보의 뜻
 언제 어떻게 프로세스가 메시지를 전송하고 메시지에
응답을 하는지 결정
공중 도메인 프로토콜들:
 RFC에 정의, 상호연동 허용 예, HTTP, SMTP
독점 프로토콜들: KaZaA
Chapter 2: Application Layer
14
2.1.4 응용은 어떤 서비스를 필요로 하는가?
신뢰적인 데이터전송
 일부 응용들은 (예. 오디오)
약간의 손실을 허용한다.
 다른 응용들은 (예.
파일전송, 텔넷) 100%
신뢰적인 데이터 전송을
요구한다.
시간(timing)
 일부 응용들은 (예.,
인터넷 전화, 대화식
게임) “유효”하기 위하여
적은 지연이 요구된다.
밴드폭
 일부 응용들은 (예.,
멀티미디어) “유효”하기
위하여 최소한의 일정
밴드폭을 요구한다.
 다른 응용들은
(“유동성있는”) 주어진
밴드폭을 사용한다.
Chapter 2: Application Layer
15
일반 응용들의 전송 서비스 요구사항
응용
파일전송
전자우편
웹문서
실시간 오디오/비데오
데이타손실
밴드폭
손실불허
손실불허
손실불허
손실허용
신축적
신축적
신축적
시간민감도
없음
없음
없음
오디오: 5kbps-1Mbps 있음, 100’s msec
비데오:10kbps-5Mbps
저장 오디오/비데오
대화식 게임
인스탄트 메시징
손실허용
손실허용
손실불허
상동
수 kbps 정도
신축적
있음, 수 초
있음, 100’s msec
있음/없음
Chapter 2: Application Layer
16
2.1.5 인터넷 트랜스포트 프로토콜이
제공하는 서비스
TCP 서비스:
 연결형: 클라이언트 서버
프로세스간 연결설정 요구
 신뢰적인 전송: 송수신
프로세스간
 흐름제어: 송신자는
수신자에게 과하지 않게
함
 혼잡제어: 네트워크가
과부하시 송신자를 억제
 제공하지 않는것: 시간과
최소 밴드폭 보장
UDP 서비스:
 송수신 프로세스간
신뢰적이지 않은
데이타전송
 제공하지 않는것:
연결설정, 신뢰성,
흐름제어, 혼잡제어,
시간 및 밴드폭 보장
질문: 그럼에도 왜 UDP를
사용하는가?
Chapter 2: Application Layer
17
인터넷 응용, 응용계층 프로토콜, 하위 전송프로토콜
응용계층 프로토콜
하위 전송 프로토콜
SMTP [RFC 2821]
Telnet [RFC 854]
HTTP [RFC 2616]
FTP [RFC 959]
독점
(예. RealNetworks)
독점
(예, 다이알패드)
TCP
TCP
TCP
TCP
TCP 또는 UDP
응용
전자메일
원격터이날접속
웹
파일전송
스트리밍멀티미디어
이너텟전화
전형적으로 UDP
Chapter 2: Application Layer
18
2장: 애플리케이션 계층
 2.1 애플리케이션 계층 프로토콜의 원리
 2.2 웹과 HTTP
 2.3 파일전송; FTP
 2.4 인터넷 전자메일
 SMTP, POP3, IMAP
 2.5 DNS- 인터넷 디렉터리 서비스
 2.6 P2P 파일공유
 2.7 TCP 소켓 프로그래밍
 2.8 UDP 소켓 프로그래밍
 2.9 간단한 웹 서버 구축하기
Chapter 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
Chapter 2: Application Layer
20
HTTP overview
HTTP: hypertext
transfer protocol
 Web’s application layer
protocol
 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
Server
running
Apache Web
server
Mac running
Navigator
Chapter 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
aside
Protocols that maintain
“state” are complex!
 past history (state) must
be maintained
 if server/client crashes,
their views of “state” may
be inconsistent, must be
reconciled
Chapter 2: Application Layer
22
HTTP connections
Nonpersistent HTTP
 At most one object is
sent over a TCP
connection.
 HTTP/1.0 uses
nonpersistent HTTP
Persistent HTTP
 Multiple objects can
be sent over single
TCP connection
between client and
server.
 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.someSchool.edu/someDepartment/home.index
jpeg images)
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
time
Chapter 2: Application Layer
24
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 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
time to
transmit
file
RTT
file
received
time
time
Chapter 2: Application Layer
26
Persistent HTTP
Nonpersistent HTTP issues:
 requires 2 RTTs per object
 OS must work and allocate
host resources for each TCP
connection
 but browsers often open
parallel TCP connections to
fetch referenced objects
Persistent HTTP
 server leaves connection
open after sending response
 subsequent HTTP messages
between same client/server
are sent over 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
 as little as one RTT for all
the referenced objects
Chapter 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)
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
Uploading form input
Post method:
 Web page often
includes form input
 Input is uploaded to
server in entity body
URL method:
 Uses GET method
 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
 GET
 POST
 HEAD

asks server to leave
requested object out of
response
HTTP/1.1
 GET, POST, HEAD
 PUT

uploads file in entity
body to path specified
in URL field
 DELETE
 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.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 data data data ...
Chapter 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
Chapter 2: Application Layer
33
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 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:



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
Cookie file
server
usual http request msg
usual http response +
ebay: 8734
Cookie file
amazon: 1678
ebay: 8734
Set-cookie: 1678
usual http request msg
cookie: 1678
usual http response msg
one week later:
Cookie file
amazon: 1678
ebay: 8734
usual http request msg
cookie: 1678
usual http response msg
server
creates ID
1678 for user
cookiespecific
action
cookiespectific
action
Chapter 2: Application Layer
36
Cookies (continued)
What cookies can bring:
 authorization
 shopping carts
 recommendations
 user session state
(Web e-mail)
aside
Cookies and privacy:
 cookies permit sites to
learn a lot about you
 you may supply name
and e-mail to sites
 search engines use
redirection & cookies
to learn yet more
 advertising companies
obtain info across
sites
Chapter 2: Application Layer
37
Web caches (proxy server)
Goal: satisfy client request without involving origin server
 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
origin
server
client
client
Proxy
server
origin
server
Chapter 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)
Chapter 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
 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
 utilization on LAN = 15%
 utilization on access link = 100%
 total delay
= Internet delay +
access delay + LAN delay
= 2 sec + minutes + milliseconds
institutional
cache
Chapter 2: Application Layer
40
Caching example (cont)
Possible solution
 increase bandwidth of access
link to, say, 10 Mbps
Consequences
origin
servers
public
Internet
 utilization on LAN = 15%
 utilization on access link = 15%
= Internet delay +
access delay + LAN delay
= 2 sec + msecs + msecs
 often a costly upgrade
10 Mbps
access link
 Total delay
institutional
network
10 Mbps LAN
institutional
cache
Chapter 2: Application Layer
41
Caching example (cont)
origin
servers
Install cache
 suppose hit rate is .4
Consequence
public
Internet
 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 = .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
 Goal: don’t send object if
cache has up-to-date cached
version
 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
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장: 애플리케이션 계층
 2.1 애플리케이션 계층 프로토콜의 원리
 2.2 웹과 HTTP
 2.3 파일전송; FTP
 2.4 인터넷 전자메일
 SMTP, POP3, IMAP
 2.5 DNS- 인터넷 디렉터리 서비스
 2.6 P2P 파일공유
 2.7 TCP 소켓 프로그래밍
 2.8 UDP 소켓 프로그래밍
 2.9 간단한 웹 서버 구축하기
Chapter 2: Application Layer
44
FTP(file transfer protocol):파일 전송 프로토콜
FTP 사용자 FTP
파일 전송
인터페이스 클라이언트
사용자
로칼 파일
시스템
FTP
서버
원격 파일
시스템
 원격 호스트 로/로부터 파일 전송
 클라이언트/서버 모델

클라이언트: 전송을 야기하는 측 (원격으로 또는 으로
부터)

서버: 원격 호스트
 ftp: RFC 959
 ftp 서버: 포트 21
Chapter 2: Application Layer
45
FTP: 별도의 제어연결과 데이터연결
 FTP 클라이언트는 TCP로




TCP 제어 연결
포트 21
트랜스포트 프로토콜을
지정하며, FTP 서버 포트 21에
접속시도
TCP 데이터연결
클라이언트는 제어연결상으로
FTP
FTP
포트 20
인증 획득
클라이언트
서버
클라이언트는 제어연결상으로
 서버는 다른 파일 전송을
명령을 보냄으로써 원격
위하여 두번째 TCP 데이터
디렉토리를 검색
연결을 연다.
서버가 파일 전송을 위해 명령을
 제어 연결:“아웃오브밴드(out
수신하면, 서버는
of band)”
클라이언트에게 TCP 데이터전송
 FTP 서버는 “상태”를 유지:
연결을 연다.
현재의 디렉토리, 인증
한 파일전송이 끝나면, 서버는
데이터연결을 끝낸다.
Chapter 2: Application Layer
46
2.3.1 FTP 명령과 응답
명령 예:
 제어 채널상으로 ASCII




텍스트로써 보낸다.
4개의 ASCII 대문자
USER username
PASS password
LIST 현재 디렉토리내의
파일 리스트를
보내진다.
 RETR filename
파일을
추출한다. (get)
 STOR filename 원격
응답 코드의 예
 상태코드와 문구 (HTTP 같음)
 3 숫자와 옵션 메시지
 331 Username OK,
password required
 125 data connection
already open; transfer
starting
 425 Can’t open data
connection
 452 Error writing file
호스트에 파일을
저장한다. (put)
Chapter 2: Application Layer
47
2장: 애플리케이션 계층
 2.1 애플리케이션 계층 프로토콜의 원리
 2.2 웹과 HTTP
 2.3 파일전송; FTP
 2.4 인터넷 전자메일
 SMTP, POP3, IMAP
 2.5 DNS- 인터넷 디렉터리 서비스
 2.6 P2P 파일공유
 2.7 TCP 소켓 프로그래밍
 2.8 UDP 소켓 프로그래밍
 2.9 간단한 웹 서버 구축하기
Chapter 2: Application Layer
48
2.4 인터넷 전자메일
출력
메시지 큐
사용자 편지함
사용자
에이전트
세 개의 주요 요소:
 사용자 에이전트
 메일 서버
메일
서버
SMTP
 simple mail transfer
protocol: SMTP
사용자 에이전트(UA)
 종종. “메일 리더mail reader”
 메일 메시지의 구성, 편집,
읽기
 예. Eudora, Outlook, elm,
Netscape Messenger
 입출력을 위해 서버에 메시지
저장
사용자
에이전트
SMTP
SMTP
메일
서버
메일
서버
사용자
에이전트
사용자
에이전트
사용자
에이전트
사용자
에이전트
Chapter 2: Application Layer
49
메일 서버
사용자
에이전트
메일 서버
 편지함(mailbox) 사용자에게
오는 메시지를 보관
 메시지 큐(message queue)
보내는 메시지 대기
 SMTP 프로토콜 전자메일을
보내기 위해 서버간 프로토콜
 클라이언트: 송신메일서버
 “서버”: 수신 메일서버
메일
서버
사용자
에이전트
SMTP
SMTP
메일
서버
메일
서버
사용자
에이전트
사용자
에이전트
사용자
에이전트
Chapter 2: Application Layer
50
2.4.1 SMTP [RFC 2821]
 클라이언트에서 서버로 신뢰적인 이메일 메시지
전송을 위하여 TCP, port25 사용
 직접전송: 송신서버에서 수신서버로
 전송 3단계
 핸드셰이킹 (greeting)
 메시지 전송
 종료
 명령/응답 관계
 명령: ASCII 텍스트
 응답: 상태코드 와 문구
 메시지는 7-비트 ASCII 이어야 한다.
Chapter 2: Application Layer
51
시나리오: 엘리스가 밥에게 메시지 전송
4) SMTP 클라이언트는 TCP
연결상으로 엘리스의
메시지를 보낸다.
5) 밥의 메일서버는 밥의
편지함에 그 메시지를
놓는다.
6) 밥은 자신의 메시지를 읽기
위해서 UA를 시작한다.
1) 멜리스는 UA에서 메시지를
구성하고 “to”
[email protected]
2) 엘리스의 UA 는 자신의
메일서버로 메시지를 보낸다.
메시지는 메시지 큐에 위치
3) 클라이언트의 SMTP 는 밥의
메일서버와 TCP 연결을
한다.
1
사용자
에이전트
2
메일
서버
메일
서버
3
4
5
6
사용자
에이전트
Chapter 2: Application Layer
52
SMTP 상호동작 예
S:
C:
S:
C:
S:
C:
S:
C:
S:
C:
C:
C:
S:
C:
S:
220 hamburger.edu
HELO crepes.fr
250 Hello crepes.fr, pleased to meet you
MAIL FROM: <[email protected]>
250 [email protected]... Sender ok
RCPT TO: <[email protected]>
250 [email protected] ... 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
 SMTP 지속(persistent)연결사용
 SMTP 메시지 (헤더와 몸체)는 7-비트
ASCII이어야 한다.
 SMTP 서버는 메시지 끝을 찾기 위하여
CRLF.CRLF 을 사용한다.
간단한 SMTP 테스트:
 telnet servername 25
 서버로 부터 220 응답이 오는지 확인
 HELO, MAIL FROM, RCPT TO, DATA,
QUIT 명령 등을 쳐보라
위의 방법은 클라이언트 없이 서버와 통신하게
한다. (리더)
Chapter 2: Application Layer
54
2.4.2 HTTP와의 비교
 HTTP: pull(누군가 올리고 필요시 가져옴) 수신자초기화
SMTP: push(송신서버가 수신서버에게 ) 송신자초기화
 둘 다 ASCII 명령/응답관계, 상태코드
 SMTP: 7 비트 ASCII 포맷
 HTTP: 응답 메시지에 각 객체들을 캡슐화
SMTP: 각 객체는 각 메시지로 만듬
Chapter 2: Application Layer
55
2.4.3 메일 메시지 포맷과 MIME
SMTP: 이메일 메시지 교환을
위한 프로토콜
RFC 822: 텍스트 메시지 포맷
표준:
 헤더



To:
From:
Subject:
헤더
빈줄
몸체
SMTP 명령들과 다름!!
 몸체

“메시지”, ASCII 문자만
Chapter 2: Application Layer
56
비-ASCII 데이터를 위한 MIME 확장
 MIME: multimedia mail extension, RFC 2045, 2056
 메시지 헤더에 추가헤더로 MIME 내용 타입 선언
MIME 버전
데이터 인코드에
사용된 방법
멀티미디어 데이터 타입,
서브타입,
매개변수 선언
인코드된 데이타
From: [email protected]
To: [email protected]
Subject: Picture of yummy crepe.
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Type: image/jpeg
base64 encoded data .....
.........................
......base64 encoded data
Chapter 2: Application Layer
57
수신된 메시지
 수신 서버는 헤더라인을 추가
Received: from crepes.fr by hamburger.edu; 12 Oct 98
15:27:39 GMT
From: [email protected]
To: [email protected]
Subject: Picture of yummy crepe.
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Type: image/jpeg
base64 encoded data .....
.........................
......base64 encoded data
Chapter 2: Application Layer
58
2.4.4 메일 액세스 프로토콜
SMTP
SMTP
액새스
프로토콜
사용자
에이전트
송신자
메일 서버
user
agent
수신자
메일 서버
 SMTP: 수신자의 서버로 전송/저장
 메일 액세스 프로토콜: 서버로 부터 읽어오기 위함



POP: Post Office Protocol [RFC 1939]
• 인증 (에이전트 <-->서버) 과 다운로드
IMAP: Internet Mail Access Protocol [RFC 1730]
• 기능강화 (더 복잡)
• 서버에 저장된 메시지를 처리
HTTP: Hotmail , Yahoo! Mail, etc.
Chapter 2: Application Layer
59
POP3 프로토콜(1)
TCP 포트 110
인증 단계
 클라이언트 명령:
user: <사용자이름>
 pass: <비밀번호>
 서버 응답
 +OK: 바로 앞 명령이 OK
 -ERR:바로 앞 명령 오류

트랜잭션 단계, client:
 list: 메시지 번호와 각 크기
 retr: 번호에 의해 가져옴
 dele: 삭제
 quit
S:
C:
S:
C:
S:
+OK POP3 server ready
user bob
+OK
pass hungry
+OK user successfully logged
C:
S:
S:
S:
C:
S:
S:
C:
C:
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 POP3 server signing off
Chapter 2: Application Layer
on
60
POP3 프로토콜(2)
 앞의 예는 “다운로드 후 삭제” 모드.
 즉, 밥은 클라이언트를 바꾸면 다시 읽지 못함
 “다운로드 후 유지”: 각 클라이언트상에서 메시지
복사본을 보유
 POP3 세션간 상태유지 안함
Chapter 2: Application Layer
61
IMAP
 모든 메시지를 한 장소 서버에 보관한다.
 처음 메시지가 도착하면 수신자 INBOX
폴더에 연결
 사용자에게 폴더를 생성하고 메시지를 보관할
수 있도록 허용
 IMAP 은 세션을 통해 사용자 상태를 유지:
폴더의 이름
 메시지 ID와 폴더 이름 대응

Chapter 2: Application Layer
62
웹기반 전자메일
HTTP
SMTP
HTTP
사용자
에이전트
송신자
메일 서버
user
agent
수신자
메일 서버
Chapter 2: Application Layer
63
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
Chapter 2: Application Layer
64
DNS: Domain Name System
People: many identifiers:

SSN, name, passport #
Domain Name System:

distributed database

application-layer protocol
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 ?
implemented in hierarchy of
many name servers
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”
Chapter 2: Application Layer
65
DNS
DNS services
 Hostname to IP
address translation
 Host aliasing

Canonical and alias
names
 Mail server aliasing
 Load distribution
 Replicated Web
servers: set of IP
addresses for one
canonical name
Why not centralize DNS?
 single point of failure
 traffic volume
 distant centralized
database
 maintenance
doesn’t scale!
Chapter 2: Application Layer
66
Distributed, Hierarchical Database
Root DNS Servers
com DNS servers
yahoo.com
amazon.com
DNS servers DNS servers
org DNS servers
pbs.org
DNS servers
edu DNS servers
poly.edu
umass.edu
DNS serversDNS servers
Client wants IP for www.amazon.com; 1st approx:
 Client queries a root 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
Chapter 2: Application Layer
67
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
a Verisign, Dulles, VA
c Cogent, Herndon, VA (also Los Angeles)
d U Maryland College Park, MD
k RIPE London (also Amsterdam,
g US DoD 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
 Top-level domain (TLD) servers: responsible
for com, org, net, edu, etc, and all top-level
country domains uk, fr, ca, jp.
Network solutions maintains servers for com TLD
 Educause for edu TLD

 Authoritative DNS servers: organization’s
DNS servers, providing authoritative
hostname to IP mappings for organization’s
servers (e.g., Web and mail).

Can be maintained by organization or service
provider
Chapter 2: Application Layer
69
Local Name Server
 Does not strictly belong to hierarchy
 Each ISP (residential ISP, company,
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.
Chapter 2: Application Layer
70
Example
root DNS server
2
 Host at cis.poly.edu
3
wants IP address for
gaia.cs.umass.edu
TLD DNS server
4
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
 puts burden of name
resolution on
contacted name
server
 heavy load?
iterated query:
 contacted server
root DNS server
3
7
6
TLD DNS server
local DNS server
dns.poly.edu
1
5
4
8
replies with name of
server to contact
 “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
 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
Chapter 2: Application Layer
73
DNS records
DNS: distributed db storing resource records (RR)
RR format: (name,
 Type=A
 name is hostname
 value is IP address
value, type, ttl)
 Type=CNAME
 name is alias name for some
“cannonical” (the real) name
www.ibm.com is really
 Type=NS
servereast.backup2.ibm.com
 name is domain (e.g.
 value is cannonical name
foo.com)
 value is IP address of
 Type=MX
authoritative name
 value is name of mailserver
server for this domain
associated with name
Chapter 2: Application Layer
74
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
Chapter 2: Application Layer
75
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
 Example: just created startup “Network Utopia”
 Register name networkuptopia.com at a registrar
(e.g., Network Solutions)


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, dns1.networkutopia.com, NS)
(dns1.networkutopia.com, 212.212.212.1, A)
 Put in authoritative server Type A record for
www.networkuptopia.com and Type MX record for
networkutopia.com
 How do people get the IP address of your Web site?
Chapter 2: Application Layer
77
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 file sharing
 2.7 Socket programming
with TCP
 2.8 Socket programming
with UDP
 2.9 Building a Web
server
Chapter 2: Application Layer
78
P2P file sharing
Example
 Alice runs P2P client
application on her
notebook computer
 Intermittently
connects to Internet;
gets new IP address
for each connection
 Asks for “Hey Jude”
 Application displays
other peers that have
copy of Hey Jude.
 Alice chooses one of
the peers, Bob.
 File is copied from
Bob’s PC to Alice’s
notebook: HTTP
 While Alice downloads,
other users uploading
from Alice.
 Alice’s peer is both a
Web client and a
transient Web server.
All peers are servers =
highly scalable!
Chapter 2: Application Layer
79
P2P: centralized directory
original “Napster” design
1) when peer connects, it
informs central server:


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
P2P: problems with centralized directory
 Single point of failure
 Performance
bottleneck
 Copyright
infringement
file transfer is
decentralized, but
locating content is
highly decentralized
Chapter 2: Application Layer
81
Query flooding: Gnutella
 fully distributed
 no central server
 public domain protocol
 many Gnutella clients
implementing protocol
overlay network: graph
 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
Chapter 2: Application Layer
82
Gnutella: protocol
 Query message
sent over existing TCP
connections
 peers forward
Query message
 QueryHit
sent over
reverse
Query
path
File transfer:
HTTP
Query
QueryHit
QueryHit
Scalability:
limited scope
flooding
Chapter 2: Application Layer
83
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: KaZaA
 Each peer is either a
group leader or assigned
to a group leader.


TCP connection between
peer and its group leader.
TCP connections between
some pairs of group
leaders.
 Group leader tracks the
content in all its
children.
ordinary peer
group-leader peer
neighoring relationships
in overlay network
Chapter 2: Application Layer
85
KaZaA: Querying
 Each file has a hash and a descriptor
 Client sends keyword query to its group
leader
 Group leader responds with matches:
 For
each match: metadata, hash, IP address
 If group leader forwards query to other
group leaders, they respond with matches
 Client then selects files for downloading

HTTP requests using hash as identifier sent to
peers holding desired file
Chapter 2: Application Layer
86
Kazaa tricks
 Limitations on simultaneous uploads
 Request queuing
 Incentive priorities
 Parallel downloading
Chapter 2: Application Layer
87
2장: 애플리케이션 계층
 2.1 애플리케이션 계층 프로토콜의 원리
 2.2 웹과 HTTP
 2.3 파일전송; FTP
 2.4 인터넷 전자메일
 SMTP, POP3, IMAP
 2.5 DNS- 인터넷 디렉터리 서비스
 2.6 P2P 파일공유
 2.7 TCP 소켓 프로그래밍
 2.8 UDP 소켓 프로그래밍
 2.9 간단한 웹 서버 구축하기
Chapter 2: Application Layer
88
소켓 프로그래밍
목표: 소켓을 사용하여 통신하는 클라이언트/서버 응용
구축 방법을 배운다.
소켓 API
소켓
 BSD4.1 UNIX, 1981 에 소개
 응용에 의해 명시적으로 생성되고,
사용되고, 해지 됨
 클라이언트/서버 파라딤
 소켓 API를 통해 두 가지 트랜스포트
서비스 타입
 비신뢰적인 데이타그램(UDP)
 신뢰적인, 바이트 스트림형(TCP)
a 호스트-내에서,
응용이생성하고,
OS가 제어하는
인터페이스( “문”) 으로써,
응용 프로세스가 다른 응용
프로세스로(부터)
메시지를 보내고 받는다.
Chapter 2: Application Layer
89
2.7.1 TCP를 이용한 소켓 프로그래밍
소켓: 응용 프로세스와 종단간 트랜스포트 프로토콜
(UCP 또는 TCP) 간의 문
TCP 서비스: 한 프로세스에서 다른 프로세스로의
바이트들의 신뢰적인 전송
응용 개발자에
의해 제어
프로세스
운영체제에
의해 제어
버퍼,
변수를
가진 TCP
프로세스
소켓
소켓
호스트 또는
서버
응용 개발자에
의해 제어
인터넷
버퍼,
변수를
가진 TCP
운영체제에
의해 제어
호스트 또는
서버
Chapter 2: Application Layer
90
클라이언트와 서버 상호작용
클라이언트는 서버에 접속해야 한다.
 서버 프로세스는 먼저 동작하고
있어야 한다.
 서버는 클라이언트의 접속을
받아들이는 소켓(문)을 생성해
놓아야 한다.
클라이언트는 다음에 의해 서버에
접속을 한다.
 클라이언트 내에 TCP 소켓을
생성하고,
 서버 프로세스의 IP주소와
포트번호를 알려주고,
 클라이언트가 소켓을 생성할때,
클라이언트 TCP는 서버 TCP에
연결한다.
 클라이언트에 의해 접속 될때,
서버 TCP 는 클라이언트와
통신하기 위한 서버 프로세스를
위한 새로운 소켓을 생성한다.
 서버가 여러 클라이언트와
대화하도록 허용한다.
 근원지 포트번호가
클라이언트들을 구별하는데
사용된다.(3장에서 자세히
배운다.)
응용 관점
TCP 는 클라이언트와 서버 사이에
바이트들의 신뢰적이고,
순서적인 전송(“파이프”)
를 제공한다.
Chapter 2: Application Layer
91
통상적인 스트림 이란 용어
 스트림이란 한 프로세스로 들어가거나 나가는 글자 열
 입력 스트림(input stream)은 처리되기 위하여 키보드 또는 소켓
같은 입력 소스에 결부되어 있다.
 출력 스트림(output stream)은 모니터 또는 소켓 같은 출력
소스에 결부되어 있다.
Chapter 2: Application Layer
92
2.7.1 TCP를 이용한 소켓 프로그래밍
Socket 함수들
 socket 새로운 통신 종단 점을 생성
 bind
자기 주소를 소켓에 알려줌
 listen
연결수락의사를 알림. 큐사이즈공개
 accept 연결시도가 될때까지 호출자를 블록
 connect 연결 설정을 시도
 send
데이터를 연결로 보냄
 receive 연결로 부터 데이터 수신
 close
연결 해제
Chapter 2: Application Layer
93
소켓 함수(1)
 소켓생성
s = socket(pf, type, protocol)
pf = 프로토콜 패밀리
PF_INET, PF_PUP, PF_APPLETAlk, PF_UNIX
type = 트랜스포트연결의 서비스종류
SOCK_STREAM, SOCK_DGRAM
protocol = 트랜스포트 프로토콜
IPPROTO_TCP, IPPROTO_UDP
 소켓종료
close(s)
Chapter 2: Application Layer
94
소켓 함수(2)
 지역주소 지정
struct sockaddr_in
{
unsigned short sin_family;
bind(s, localaddr, addrlen)
unsigned short sin_port;
struct in_addr sin_addr;
 목적지 주소로 연결
char sin_zero[8];
connect(s, destaddr, addrlen)
//사용안함
 message에 있는 메시지 전송 }
send(s, message, length, flags)
IP주소
 메시지를 buffer에 저장
recv(s, buffer, length, flags)
포트번호
Chapter 2: Application Layer
95
소켓 함수(3)
 서버를위한 큐 길이
listen(s, qlength)
서버가 listen을 호출하면, OS는 동시 들어오는
연결요청을 큐에 저장하도록 하는 큐의 길이를 지정
연결수락
ns = accept(s, addr, addrlen)
일단 소켓이 설정되면, accept를 호출하고 연결
요청이 들어올때까지 서버를 블록한다. 연결요청이
들어오면, 서버는 새로운 소켓(ns)를 생성하여 연결
요청에 응답하고, 서버는 새로운 연결호출을 기다리기
위하여 다시 accept를 호출한다. addr은 요청자 주소
Chapter 2: Application Layer
96
클라이언트/서버 소켓 상호동작: TCP
서버
클라이언트
소켓 생성
s = socket(pf, type, protocol)
bind(s, lad, adln)
listen(s, qln)
ns = accept(s,ad, 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 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 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 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 sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
//사용안함
}
ServAddr
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 ServAddr;
char msg[100];
unsigned int msgStrLen;
int bytesSent=0;
Chapter 2: Application Layer
100
클라이언트 예(2/3)
msg
host to network
a b c /0
gets(msg);
//assign the server address infomation
memset(&ServAddr, 0, sizeof(ServAddr));
ServAddr.sin_family=AF_INET;
ServAddr.sin_port=htons(9876);
ServAddr.sin_addr.s_addr=inet_addr("211.211.211.207");
21110=110100112 = 1x27+1x26+1x24+1x21+1x20
ServAddr
AF_NET
9876
11010011 11010011
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 sockaddr *) &ServAddr, sizeof(struct sockaddr_in));
//send data
msgStrLen=strlen(msg);
for(;;){
bytesSent=send(sock, msg, msgStrLen, 0);
printf("bytesSent : %d \n",bytesSent);
//scanf("%s",msg);
gets(msg);
msgStrLen=strlen(msg);
}
close(sock);
exit(0);
}
Chapter 2: Application Layer 102
서버 예(1/2)
#include <stdio.h>
ServAddr.sin_family=AF_INET;
#include <sys/socket.h>
//ServAddr.sin_addr.s_addr=htol(INADDR_ANY);
#include <arpa/inet.h>
ServAddr.sin_addr.s_addr=inet_addr("211.211.211.207");
#include <stdlib.h>
ServAddr.sin_port=htons(9876);
#include <string.h>
//server socket creation
#include <unistd.h>
sSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
int main(void)
{
//bind
int sSock;
bind(sSock,
int cSock;
(struct sockaddr *)&ServAddr, sizeof(struct sockaddr_in));
struct sockaddr_in ServAddr;
struct sockaddr_in clntAddr; //listen
unsigned int clntLen;
listen(sSock, 5);
char RcvBuffer[100];
int i=0, bytesRcvd;
memset(&ServAddr, 0, sizeof(ServAddr));
Chapter 2: Application Layer
103
서버 예(2/2)
//accpet
clntLen = sizeof(struct sockaddr_in);
cSock = accept(sSock, (struct sockaddr *)&clntAddr, &clntLen );
printf("ip : %s\n", inet_ntoa(clntAddr.sin_addr));
bytesRcvd=recv(cSock, RcvBuffer, sizeof(RcvBuffer), 0);
while(bytesRcvd > 0){
//receive
printf("bytesRcvd 1: %d \n", bytesRcvd);
RcvBuffer[bytesRcvd]='\0';
printf("received string 1: %s\n",RcvBuffer);
//printf("start for %d\n", bytesRcvd);
bytesRcvd=0;
printf("bytesRcvd 2: %d \n", bytesRcvd);
bytesRcvd=recv(cSock, RcvBuffer, sizeof(RcvBuffer), 0);
printf("bytesRcvd 3: %d \n", bytesRcvd);
RcvBuffer[bytesRcvd]='\0';
printf("received string 3: %s\n",RcvBuffer);
//bytesRcvd=0;
printf("end for %d\n", bytesRcvd);
//
i++;
}
close(cSock);
exit(0);
}
Chapter 2: Application Layer
104
Socket programming with TCP
output
stream
inFromUser
Client
Process
process
input
stream
outToServer
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, prints modified
line from socket
(inFromServer stream)
monitor
inFromServer
Example client-server app:
keyboard
input
stream
client
TCP
clientSocket
socket
to network
TCP
socket
from network
Chapter 2: Application Layer
105
Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
Create
input stream
Create
client socket,
connect to server
Create
output stream
attached to socket
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
Chapter 2: Application Layer
106
Example: Java client (TCP), cont.
Create
input stream
attached to socket
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
Send line
to server
outToServer.writeBytes(sentence + '\n');
Read line
from server
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Chapter 2: Application Layer
107
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 clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
Chapter 2: Application Layer
108
Example: Java server (TCP), cont
Create output
stream, attached
to socket
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
Write out line
to socket
outToClient.writeBytes(capitalizedSentence);
}
}
}
End of while loop,
loop back and wait for
another client connection
Chapter 2: Application Layer
109
2장: 애플리케이션 계층
 2.1 애플리케이션 계층 프로토콜의 원리
 2.2 웹과 HTTP
 2.3 파일전송; FTP
 2.4 인터넷 전자메일
 SMTP, POP3, IMAP
 2.5 DNS- 인터넷 디렉터리 서비스
 2.6 P2P 파일공유
 2.7 TCP 소켓 프로그래밍
 2.8 UDP 소켓 프로그래밍
 2.9 간단한 웹 서버 구축하기
Chapter 2: Application Layer
110
UDP 소켓 프로그래밍
UDP: 클라이언트 서버간에
“connection” 없음
 핸드셰이킹 없음
 송신자는 각 패킷 마다
IP 주소와 포트번호를
일일이 명시
 서버는 수신된 패킷으로
부터 송신자의 IP주소와
포트번호를 추출
 UDP: 전송된 데이터는
손실되거나 순서가
바뀔수도 있음
응용관점
UDP 는 클라이언트와 서버간에
바이트들의 묶음(데이타그램)들을
비신뢰적으로 전송한다.
Chapter 2: Application Layer
111
소켓함수
 송신
sendto(s, message, length, flags, destaddr, addrlen)
 수신
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)
소켓 생성
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)
sendto(s, msg, ln, f, ad, adln)
데이터(응답)
recvfrom(s, buf, ln, f, fad, adln)
Chapter 2: Application Layer
113
클라이언트/서버 소켓 상호동작: 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:
serverSocket =
DatagramSocket()
read request from
serverSocket
write reply to
serverSocket
specifying client
host address,
port number
Client
create socket,
clientSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read reply from
clientSocket
close
clientSocket
Chapter 2: Application Layer
115
Example: Java client (UDP)
input
stream
Client
process
monitor
inFromUser
keyboard
Process
Input: receives
packet (TCP
received “byte
stream”)
UDP
packet
receivePacket
packet (TCP sent
“byte stream”)
sendPacket
Output: sends
client
UDP
clientSocket
socket
to netw ork
UDP
packet
UDP
socket
f rom netw ork
Chapter 2: Application Layer
116
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
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Chapter 2: Application Layer
117
Example: Java client (UDP), cont.
Create datagram
with data-to-send,
length, IP addr, port
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
Send datagram
to server
clientSocket.send(sendPacket);
Read datagram
from server
clientSocket.receive(receivePacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
Chapter 2: Application Layer
118
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
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
Create space for
received datagram
Receive
datagram
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
Chapter 2: Application Layer
119
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
Get IP addr
port #, of
sender
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
Create datagram
to send to client
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram
to socket
serverSocket.send(sendPacket);
}
}
}
End of while loop,
loop back and wait for
another datagram
Chapter 2: Application Layer
120
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 file sharing
 2.7 Socket programming
with TCP
 2.8 Socket programming
with UDP
 2.9 Building a Web
server
Chapter 2: Application Layer
121
Building a simple Web server
 handles one HTTP




request
accepts the request
parses header
obtains requested file
from server’s file
system
creates HTTP response
message:

 after creating server,
you can request file
using a browser (eg IE
explorer)
 see text for details
header lines + file
 sends response to client
Chapter 2: Application Layer
122
Chapter 2: Summary
Our study of network apps now complete!
 Application architectures
 client-server
 P2P
 hybrid
 application service
requirements:

 specific protocols:
 HTTP
 FTP
 SMTP, POP, IMAP
 DNS
 socket programming
reliability, bandwidth,
delay
 Internet transport
service model


connection-oriented,
reliable: TCP
unreliable, datagrams: UDP
Chapter 2: Application Layer
123
Chapter 2: Summary
Most importantly: learned about protocols
 typical request/reply
message exchange:


client requests info or
service
server responds with
data, status code
 message formats:
 headers: fields giving
info about data
 data: info being
communicated
 control vs. data msgs
in-band, out-of-band
centralized vs. decentralized
stateless vs. stateful
reliable vs. unreliable msg
transfer
“complexity at network
edge”





Chapter 2: Application Layer
124