Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2: Application Layer

Similar presentations


Presentation on theme: "Chapter 2: Application Layer"— Presentation transcript:

1 Chapter 2: Application Layer
Our goals: conceptual, implementation aspects of network application protocols transport-layer service models client-server paradigm learn about protocols by examining popular application-layer protocols HTTP SMTP / POP3 / IMAP DNS programming network applications socket API 2: Application Layer

2 Chapter 2 outline 2.1 Principles of app layer protocols
clients and servers app requirements 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS Socket programming with TCP Socket programming with UDP 2: Application Layer

3 Network applications: some jargon
Process: program running within a host. within same host, two processes communicate using interprocess communication (defined by OS). processes running in different hosts communicate with an application-layer protocol user agent: interface between user and network application implements user interface & application-layer protocol Web: browser mail reader streaming audio/video: media player 2: Application Layer

4 Applications and application-layer protocols
Application: communicating, distributed processes e.g., , Web, P2P file sharing, instant messaging running in end systems (hosts) exchange messages to implement application Application-layer protocols one “piece” of an app define messages exchanged by apps and actions taken use communication services provided by lower layer protocols (TCP, UDP) application transport network data link physical 2: Application Layer

5 App-layer protocol defines
Types of messages exchanged, eg, request & response messages Syntax of message types: what fields in messages & how fields are delineated Semantics of the fields, i.e, meaning of information in fields Rules for when and how processes send & respond to messages Public-domain protocols: defined in RFCs allows for interoperability eg, HTTP, SMTP Proprietary protocols: eg, Internet phone 2: Application Layer

6 Client-server paradigm
Typical network app has two pieces: client and server application transport network data link physical reply request Client: initiates contact with server (“speaks first”) typically requests service from server, Web: client implemented in browser; in mail reader Server: provides requested service to client e.g., Web server sends requested Web page, mail server delivers 2: Application Layer

7 Processes communicating across network
process sends/receives messages to/from its socket socket analogous to door sending process shoves message out door sending process assumes transport infrastructure on other side of door which brings message to socket at receiving process process TCP with buffers, variables socket host or server process TCP with buffers, variables socket host or server controlled by app developer Internet controlled by OS API (Application Program Interface) : (1) choice of transport protocol; (2) ability to fix a few parameters 2: Application Layer

8 Addressing processes:
For a process to receive messages, it must have an identifier Every host has a unique 32-bit IP address Q: does the IP address of the host on which the process runs suffice for identifying the process? Answer: No, many processes can be running on same host Identifier includes both the IP address and port numbers associated with the process on the host. Example port numbers: HTTP server: 80 Mail server: 25 2: Application Layer

9 What transport service does an app need?
Data loss some apps (e.g., audio/video) can tolerate some loss other apps (e.g., file transfer, telnet) require 100% reliable data transfer Bandwidth some apps (e.g., multimedia) require minimum amount of bandwidth to be “effective” other apps (“elastic apps”, e.g., , file transfer) make use of whatever bandwidth they get Timing some apps (e.g., Internet telephony, interactive games) require low delay to be “effective” 2: Application Layer

10 Transport service requirements of common apps
Application file transfer Web documents real-time audio/video stored audio/video interactive games instant messaging Data loss no loss loss-tolerant Bandwidth elastic audio: 5kbps-1Mbps video:10kbps-5Mbps same as above few kbps up Time Sensitive no yes, 100’s msec yes, few secs yes and no 2: Application Layer

11 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 bandwidth guarantees UDP service: unreliable data transfer between sending and receiving process does not provide: connection setup, reliability, flow control, congestion control, timing, or bandwidth guarantee Q: why bother? Why is there a UDP? 2: Application Layer

12 Internet apps: application, transport protocols
layer protocol SMTP [RFC 2821] Telnet [RFC 854] HTTP [RFC 2616] FTP [RFC 959] proprietary (e.g. RealNetworks) (e.g., Dialpad) Underlying transport protocol TCP TCP or UDP typically UDP Application remote terminal access Web file transfer streaming multimedia Internet telephony 2: Application Layer

13 Chapter 2 outline 2.1 Principles of app layer protocols
clients and servers app requirements 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS Socket programming with TCP Socket programming with UDP 2: Application Layer

14 Web and HTTP First some jargon Web page consists of objects
Object can be HTML file, JPEG image, Java applet, audio clip, … Web page consists of base HTML-file which includes several referenced objects Each object is addressable by a URL Example URL: host name path name 2: Application Layer

15 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,2616 HTTP request PC running Explorer HTTP response HTTP request Server running Apache Web server HTTP response Mac running Navigator 2: Application Layer

16 HTTP overview (continued)
Uses TCP: client initiates TCP connection (creates socket) to server, port 80 server accepts TCP connection from client HTTP messages (application-layer 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 2: Application Layer

17 HTTP connections Nonpersistent HTTP
Only 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 2: Application Layer

18 Nonpersistent HTTP (contains text, references to 10 jpeg images) Suppose user enters URL 1a. HTTP client initiates TCP connection to HTTP server (process) at on port 80 1b. HTTP server at host waiting for TCP connection at port 80. “accepts” connection, notifying client 2. HTTP client sends HTTP request message into TCP connection socket. Message indicates that client wants object someDepartment/home.html 3. HTTP server receives request message, forms response message containing requested object, and sends message into its socket time 2: Application Layer

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

20 Response time modeling
time to transmit file initiate TCP connection RTT request received time Definition of RRT (round-trip time: 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 2: Application Layer

21 Persistent HTTP Nonpersistent HTTP issues:
requires 2 RTTs per object OS must 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 2: Application Layer

22 HTTP request message two types of HTTP messages: request, response
ASCII (human-readable format) request line (GET, POST, HEAD commands) GET /somedir/page.html HTTP/1.1 Host: User-agent: Mozilla/4.0 Connection: close Accept-language:fr (extra carriage return, line feed) header lines Carriage return, line feed indicates end of message 2: Application Layer

23 HTTP request message: general format
2: Application Layer

24 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: 2: Application Layer

25 Method types HTTP/1.0 GET POST HEAD HTTP/1.1 GET, POST, HEAD PUT
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 2: Application Layer

26 HTTP response message status line (protocol status code status phrase)
HTTP/ OK Connection: close Date: Thu, 06 Aug :00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Jun Content-Length: 6821 Content-Type: text/html data data data data data ... header lines data, e.g., requested HTML file 2: Application Layer

27 HTTP response status codes
In first line in response message. A few sample codes: 200 OK request succeeded, requested object included 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

28 Conditional GET: client-side caching
server Goal: don’t send object if client has up-to-date cached version client: specify date of cached copy in HTTP request If-modified-since: <date> server: response contains no object if cached copy is up-to-date: HTTP/ Not Modified HTTP request msg If-modified-since: <date> object not modified HTTP response HTTP/1.0 304 Not Modified HTTP request msg If-modified-since: <date> object modified HTTP response HTTP/ OK <data> 2: Application Layer

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

30 Chapter 2 outline 2.1 Principles of app layer protocols
clients and servers app requirements 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS Socket programming with TCP Socket programming with UDP 2: Application Layer

31 Electronic Mail Three major components: SMTP SMTP SMTP user agents
user mailbox outgoing message queue user agent Three major components: user agents mail servers simple mail transfer protocol: SMTP User Agent a.k.a. “mail reader” composing, reading, replying to mail messages e.g., Eudora, Outlook, elm, Netscape Messenger mail server user agent SMTP mail server user agent SMTP mail server SMTP user agent user agent user agent 2: Application Layer

32 Electronic Mail: mail servers
user agent Mail Servers mailbox contains incoming messages for user message queue of outgoing (to be sent) mail messages SMTP protocol between mail servers to send messages client: sending mail server server: receiving mail server mail server user agent SMTP mail server user agent SMTP mail server SMTP user agent user agent user agent 2: Application Layer

33 Electronic Mail: SMTP [RFC 2821]
uses TCP to reliably transfer 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 2: Application Layer

34 Scenario: Alice sends message to Bob
1) Alice uses UA to compose message and “to” 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 mail server mail server 1 user agent user agent 2 3 6 4 5 2: Application Layer

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

36 Try SMTP interaction for yourself:
telnet servername 25 (cs mail server: mail.cs.iastate.edu) see 220 reply from server enter HELO, MAIL FROM, RCPT TO, DATA, QUIT commands above lets you send without using client (reader) 2: Application Layer

37 SMTP: final words Comparison with HTTP:
SMTP uses persistent connections SMTP requires message (header & body) to be in 7-bit ASCII SMTP server uses CRLF.CRLF to determine end of message Comparison with HTTP: both have ASCII command/response interaction, status codes HTTP: pull; SMTP: push HTTP: each object encapsulated in its own response msg SMTP: multiple objects sent in multipart msg 2: Application Layer

38 Mail message format header body
SMTP (RFC 2821): protocol for exchanging messages RFC 822: standard for text message format: header lines, e.g., To: From: Subject: different from SMTP commands! body the “message”, ASCII characters only header blank line body 2: Application Layer

39 Message format: multimedia extensions
MIME: Multipurpose Internet Mail Extensions, RFC 2045, 2046 additional lines in message header declare MIME content type From: To: Subject: Picture of yummy crepe. MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Type: image/jpeg base64 encoded data ..... ......base64 encoded data MIME version method used to encode data multimedia data type, subtype, parameter declaration encoded data 2: Application Layer

40 MIME types Content-Type: type/subtype; parameters
Text example subtypes: plain, html Image example subtypes: jpeg, gif Audio exampe subtypes: basic (8-bit mu-law encoded), 32kadpcm (32 kbps coding) Video example subtypes: mpeg, quicktime Application other data that must be processed by an application before “viewable” example subtypes: msword, postscript 2: Application Layer

41 Multipart Type From: alice@crepes.fr To: bob@hamburger.edu
Subject: Picture of yummy crepe. MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=StartOfNextPart --StartOfNextPart Dear Bob, Please find a picture of a crepe. Content-Transfer-Encoding: base64 Content-Type: image/jpeg base64 encoded data ..... ......base64 encoded data Do you want the recipe? 2: Application Layer

42 Mail access protocols SMTP SMTP access protocol
user agent user agent sender’s mail server receiver’s mail server SMTP: delivery/storage to receiver’s server Mail access protocol: retrieval from server POP3: Post Office Protocol-Version 3 [RFC 1939] authorization (agent <-->server) and download IMAP: Internet Mail Access Protocol [RFC 2060] more features (more complex) manipulation of stored msgs on server HTTP: Hotmail , Yahoo! Mail, etc. 2: Application Layer

43 POP3 protocol C: list authorization phase client commands:
S: +OK POP3 server ready C: user bob S: +OK C: pass hungry S: +OK user successfully logged on authorization phase client commands: user: username pass: password server responses +OK and -ERR transaction phase, client: list: list message numbers retr: retrieve message by number dele: delete Quit Update phase: server deletes the messages marked for deletion C: list S: 1 498 S: 2 912 S: . C: retr 1 S: <message 1 contents> C: dele 1 C: retr 2 S: <message 2 contents> C: dele 2 C: quit S: +OK POP3 server signing off 2: Application Layer

44 POP3 (more) and IMAP More about POP3 IMAP
Previous example uses “download and delete” mode. Bob cannot re-read if he changes client “Download-and-keep”: copies of messages on different clients IMAP Keep all messages in one place: the server Allows user to organize messages in folders IMAP keeps user state across sessions: names of folders and mappings between message IDs and folder name 2: Application Layer

45 Chapter 2 outline 2.1 Principles of app layer protocols
clients and servers app requirements 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS Socket programming with TCP Socket programming with UDP 2: Application Layer

46 DNS: Domain Name System
People: many identifiers: SSN, name, passport # Internet hosts: IP address (e.g ) - used by routers “name”(e.g., popeye.cs.iastate.edu) - used by humans Q: map between IP addresses and name ? Domain Name System: distributed database implemented in a hierarchy of many name servers application-layer protocol host, name servers to communicate to resolve names (address/name translation) core Internet function, implemented as application-layer protocol (use UDP and port 53) complexity at network’s “edge” 2: Application Layer

47 DNS name servers no server has all name-to-IP address mappings
Why not centralize DNS? single point of failure traffic volume distant centralized database maintenance doesn’t scale! no server has all name-to-IP address mappings local name servers: each local ISP has a local (default) name server host DNS query first goes to local name server authoritative name server: for a host: stores that host’s IP address, name can perform name/address translation for that host’s name 2: Application Layer

48 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 b USC-ISI Marina del Rey, CA l ICANN Marina del Rey, CA e NASA Mt View, CA f Internet Software C. Palo Alto, CA i NORDUnet Stockholm k RIPE London m WIDE Tokyo a NSI Herndon, VA c PSInet Herndon, VA d U Maryland College Park, MD g DISA Vienna, VA h ARL Aberdeen, MD j NSI (TBD) Herndon, VA 13 root name servers worldwide 2: Application Layer

49 authorititive name server
Simple DNS example root name server host surf.eurecom.fr wants IP address of gaia.cs.umass.edu 1. contacts its local DNS server, dns.eurecom.fr 2. dns.eurecom.fr contacts root name server, if necessary 3. root name server contacts authoritative name server, dns.umass.edu, if necessary 2 4 3 5 local name server dns.eurecom.fr authorititive name server dns.umass.edu 1 6 requesting host surf.eurecom.fr gaia.cs.umass.edu 2: Application Layer

50 DNS example Root name server: may not know authoritative name server
may know intermediate name server: who to contact to find authoritative name server 2 6 7 3 local name server dns.eurecom.fr intermediate name server dns.umass.edu 4 5 1 8 authoritative name server dns.cs.umass.edu requesting host surf.eurecom.fr gaia.cs.umass.edu 2: Application Layer

51 DNS: iterative queries
root name server recursive query: puts burden of name resolution on contacted name server iterative query: contacted server replies with name of server to contact “I don’t know this name, but ask this server” iterative query 2 3 4 7 local name server dns.eurecom.fr intermediate name server dns.umass.edu 5 6 1 8 authoritative name server dns.cs.umass.edu requesting host surf.eurecom.fr gaia.cs.umass.edu 2: Application Layer

52 DNS caching once (any) name server learns mapping, it caches mapping
cache entries timeout (disappear) after some time reduce DNS delay and DNS traffic 2: Application Layer

53 RR format: (name, value, type, ttl)
DNS records DNS: distributed db storing resource records (RR) RR format: (name, value, type, ttl) Type=A name is hostname value is IP address e.g. (relay1.bar.foo.com, , A) Type=CNAME name is alias name for some “canonical” (the real) name value is canonical name e.g. (foo.com, relay1.bar.foo.com, CNAME) Type=NS name is domain value is hostname of authoritative name server for this domain e.g. (foo.com, dns.foo.com, NS) Type=MX value is canonical name of a mail server that has an alias hostname name e.g. (foo.com, mail.bar.foo.com, MX) 2: Application Layer

54 DNS protocol, messages DNS protocol : query and reply messages, both with same message format message header identification: 16 bit # for query, reply to query uses same # flags: query (0) or reply (1) reply is authoritative recursion desired recursion available 2: Application Layer

55 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

56 Chapter 2 outline 2.1 Principles of app layer protocols
clients and servers app requirements 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS Socket programming with TCP Socket programming with UDP 2: Application Layer

57 Socket programming Socket API
Goal: learn how to build client/server application that communicate using sockets Socket API client/server paradigm explicitly created, used, released by apps two types of transport service via socket API: UDP socket: unreliable datagram TCP socket: reliable, byte-stream-oriented 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 socket 2: Application Layer

58 Socket-programming using TCP
Socket: a door between application process and transport protocol (UCP or TCP) TCP service: reliable, in-order transfer of bytes from one process to another controlled by application developer controlled by application developer process TCP with buffers, variables socket process TCP with buffers, variables socket controlled by operating system controlled by operating system internet host or server host or server 2: Application Layer

59 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 establish a connection to server’s socket When contacted by client, server TCP creates new socket for server process to communicate with client allows server to talk with multiple clients application viewpoint TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server 2: Application Layer

60 Socket Programming Using TCP: Flow Diagram
client server socket() socket() bind() listen() TCP 3-way handshake connect() accept() Data (request) write() read() Data (reply) read() write() close() close() 2: Application Layer

61 The socket() System Call
int socket(int family, int type, int protocol) address family: AF_INET for Internet addresses socket type: SOCK_STREAM: supported by TCP. Connection-oriented and reliable. Message boundaries are not preserved. SOCK_DGRAM: supported by UDP. Connectionless and unreliable. Message boundaries are maintained. protocol: 0 Return value: a socket descriptor that can be used to reference the socket in subsequent system calls. –1 on error. Example: sock=socket(AF_INET, SOCK_STREAM, 0) returns a TCP stream socket 2: Application Layer

62 The bind() System Call int bind(int sockfd, struct sockaddr *addr, int addrlen) Bind an address to the socket sockfd: socket descriptor struct sockaddr{ short sa_family; /*address family*/ char sa_data[14]; /*up to 14 bytes of address*/ } addrlen: size of addr structure Return value: 0 for success, -1 for error. 2: Application Layer

63 Internet Domain Address
/* Internet socket address structure */ struct sockaddr_in { short sin_family; /*AF_INET*/ u_short sin_port; /*16-bit port no., network byte order */ struct in_addr sin_addr;/*32-bit Internet address, network byte order*/ char sin_zero[8]; /*unused*/ }; /* Internet address */ struct in_addr { u_long s_addr; 2: Application Layer

64 The bind() System Call: An Example
int sockfd; struct sockaddr_in myaddr; if ((sockfd=socket(AF_INET, SOCK_STREAM, 0))<0) {/*handle error*/} myaddr.sin_family=AF_INET; myaddr.sin_port=htons(5100); //all ports below 1024 are RESERVED myaddr.sin_addr.s_addr=htonl(INADDR_ANY); if (bind(sockfd, (struct sockaddr *) &myaddr, sizeof(myaddr))<0) Note: cast sockaddr_in to sockaddr in bind(). 2: Application Layer

65 Listen(), Accept(), Connect()
int listen(int sockfd, int maxwaiting) Called by server, ready to accept requests Initialize a queue for incoming connection requests. int accept(int sockfd, struct sockaddr *fromaddr, int *addrlen) sockfd used for accepting incoming connection requests Take the first pending connection request off the queue and create a new socket (return value) for communicating with client The address of the client socket is returned in fromaddr Block until client connects int connect(int sockfd, struct sockaddr *toaddr, int addrlen) Called by client Blocking, return when accepted 2: Application Layer

66 Sending and Receiving Data
int read(int sockfd, char *buffer, int n) read n bytes from a socket and store them in buffer. int write(int sockfd, char *buffer, int n) write n bytes stored in buffer to a socket read and write return the number of bytes read/written or -1 if they fail. 2: Application Layer

67 A Simple Server Using TCP Socket
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define MYPORT // the port users will be connecting to #define BACKLOG // how many pending connections queue will hold int main() { int sockfd, new_fd; // listen on sockfd, new connection on new_fd struct sockaddr_in my_addr; // my address information struct sockaddr_in their_addr; // client's address information int sin_size; 2: Application Layer

68 A Simple Server Using TCP Socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } my_addr.sin_family = AF_INET; my_addr.sin_port = htons(MYPORT); my_addr.sin_addr.s_addr = htonl(INADDR_ANY); // automatically fill with my IP if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); if (listen(sockfd, BACKLOG) == -1) { perror("listen"); 2: Application Layer

69 A Simple Server Using TCP Socket
while(1) { sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr)); if (write(new_fd, "Hello, world!\n", 14) < 0) { perror("send"); exit(1); close(new_fd); 2: Application Layer

70 A Simple Client Using TCP Socket
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #define PORT 3490 // the port client will be connecting to #define MAXDATASIZE 100 // max number of bytes we can get at once int main(int argc, char *argv[]) { int sockfd, numbytes; char buf[MAXDATASIZE]; struct hostent *he; struct sockaddr_in their_addr; // server's address information 2: Application Layer

71 A Simple Client Using TCP Socket
if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); if ((he=gethostbyname(argv[1])) == NULL) { // get the host info perror("gethostbyname"); their_addr.sin_family = AF_INET; their_addr.sin_port = htons(PORT); memcpy(&their_addr.sin_addr, he->h_addr, he->h_length); 2: Application Layer

72 A Simple Client Using TCP Socket
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1 { perror("connect"); exit(1); } if ((numbytes=read(sockfd, buf, MAXDATASIZE)) < 0) { perror("read"); printf("Received: %s",buf); close(sockfd); 2: Application Layer

73 Chapter 2 outline 2.1 Principles of app layer protocols
clients and servers app requirements 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.5 DNS Socket programming with TCP Socket programming with UDP 2: Application Layer

74 Socket programming with UDP
UDP: no “connection” between client and server no handshaking sender explicitly specifies the address of the destination for each packet 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

75 Socket Programming Using UDP: Flow Diagram
client server socket() socket() bind() Data (request) sendto() recvfrom() Data (reply) sendto() recvfrom() close() close() 2: Application Layer

76 Sending via UDP Socket: sendto()
int sendto (int sockfd, char *buff, int bufflen, int flags, struct sockaddr *toaddr, int tolen) sockfd: socket descriptor buff: a set of consecutive memory locations holding the message to send bufflen: number of bytes to send flags: 0 toaddr: address of sockaddr_in structure holding destination address info. tolen: length of destination address Return value: length of data actually sent. –1 if error. 2: Application Layer

77 Reading from UDP Socket: recvfrom()
int recvfrom (int sockfd, char *buff, int bufflen, int flags, struct sockaddr *fromaddr, int *fromlen) sockfd: socket descriptor buff: a set of consecutive memory locations holding the message to be received bufflen: number of bytes to read flags: 0 fromaddr: address of sockaddr_in structure containing address info of socket that sent the data. A returned value. tolen: size of the address structure. A returned value. Retun value: number of bytes actually received. –1 of error. 2: Application Layer

78 A Simple Example Server Using UDP Socket
#include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #define MY_PORT_ID 6090 main (int argc, char *argv[ ]) { int sockid, nread, addrlen; struct sockaddr_in myaddr, client_addr; char msg[50]; if ((sockid=socket(AF_INET, SOCK_DGRAM, 0))<0) {printf(“server: socket error: %d\n”, errno); exit(0);} myaddr.sin_family=AF_INET; myaddr.sin_port=htons(MY_PORT_ID); myaddr.sin_addr.s_addr=htonl(INADDR_ANY); if (bind(sockid, (struct sockaddr *) &myaddr, sizeof(myaddr)))<0 {printf(“server: bind fail: %d\n”, errno); exit(0);}; nread=recvfrom(sockid,msg,11,0,(struct sockaddr*)&client_addr, &addrlen)); If (nread>0) printf(“server: message is %s\n”,msg); close(sockid); } 2: Application Layer

79 A Simple Example Client Using UDP Socket
server_addr.sin_family=AF_INET; server_addr.sin_port=htons(SERVER_PORT_ID); server_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR); sprintf(msg, “hello world”); retcode=sendto(sockid,msg,11,0,(struct sockaddr*)&server_addr, sizeof(server_addr)); If (retcode==-1) {printf(“client: sendto failed: %d\n”,errno); exit(0);} close(sockid); } #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #define SERVER_PORT_ID 6090 #define SERV_HOST_ADDR “ ” main (int argc, char *argv[ ]) { int sockid, retcode; struct sockaddr_in myaddr, server_addr; char msg[12]; if ((sockid=socket(AF_INET, SOCK_DGRAM, 0))<0) {printf(“client: socket error: %d\n”, errno); exit(0);} 2: Application Layer

80 Chapter 2: Summary Our study of network apps now complete!
application service requirements: reliability, bandwidth, delay client-server paradigm Internet transport service model connection-oriented, reliable: TCP unreliable, datagrams: UDP specific protocols: HTTP SMTP3, POP, IMAP DNS socket programming 2: Application Layer

81 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 2: Application Layer


Download ppt "Chapter 2: Application Layer"

Similar presentations


Ads by Google