0% found this document useful (0 votes)
8 views61 pages

Network Programming

The document provides an overview of network programming, detailing the structure and functionality of the Internet, including the TCP/IP protocol stack and its various layers. It explains the roles of different layers such as the physical, data link, network, transport, and application layers, as well as concepts like IP addresses, MAC addresses, and the client-server model. Additionally, it covers socket programming, including the use of sockets for communication between clients and servers.

Uploaded by

UTKARSH AGARWAL
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views61 pages

Network Programming

The document provides an overview of network programming, detailing the structure and functionality of the Internet, including the TCP/IP protocol stack and its various layers. It explains the roles of different layers such as the physical, data link, network, transport, and application layers, as well as concepts like IP addresses, MAC addresses, and the client-server model. Additionally, it covers socket programming, including the use of sockets for communication between clients and servers.

Uploaded by

UTKARSH AGARWAL
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Network Programming

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 1


Internet

● Network is a set of connected


machines that can communicate
with each other using a protocol
and a set of rules for
communication
● Internet is a global network of
computers
● The web sends data between
browsers and servers using the
Internet
● The Internet can be used for
more than the web

2
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 2
Internet

● US Military
○ DARPANet
○ Build a network capable of communicating while withstanding failures
● TCP/IP designed with reliability and fault tolerance
● What about security?

3
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 3
Protocol Suite

● OSI Model and TCP/IP Model


○ Partition network into layers such that each layer has protocols and uses
services from layers below it

4
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 4
TCP/IP Protocol Stack

5
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 5
Layers

[Link]
6
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 6
Layers

[Link]
7
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 7
Layers

[Link]
8
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 8
Physical and Datalink Layer

● Physical layer sends bits from one device to another


○ Encodes bits to send them over a physical link
● Datalink layer encodes messages into frames (groups of bits)
● E.g., Ethernet on a physical wire
● Datalink layer relies on physical layer
● Set of computers on LAN can directly address
each other
● Frames contain source, destination and data

9
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 9
MAC Address

● MAC (media access control) address identifies an equipment on


the network uniquely
● 6-byte address
○ E.g., ac:de:48:00:11:22
● First three bytes identify manufacturers and last three identify the
device

10
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 10
Network Layer

● Send packets from one device to another


● Messages are encoded as packets and rely on sending frames from
one device to another
● Instead of addressing the machine directly
send via other devices

11
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 11
Network Layer

12
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 12
Network Layer

● Forwarding tables at each router populated by routing protocols


○ RIP, OSPF, BGP, …
● BGP misconfigurations are a serious problem
● Routing protocols update tables based on cost of each route
○ Exchange tables with neighbors, or everyone (depends on protocol)
○ Use neighbor leading to the shortest path

13
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 13
Internet Protocol

● Universal protocol that all devices use to transmit data over the
Internet
● IP address: An address that identifies a device on the Internet
○ IPv4 is 32 bits, typically written as 4 decimal octets, e.g. [Link]
○ IPv6 is 128 bits, typically written as 8 groups of 2 hex bytes:
fe80::83a:1a1f:6871:2efb
● Unique addresses that help nodes make decisions on where to
forward the packet

14
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 14
Reliability

● IP does not guarantee reliability


○ Reliability ensures that packets are received correctly or not at all
● IP provides a best-effort service
○ Packets may not be delivered
○ Packets may be delivered out-of-order
○ Packets may be corrupted
● Upto the higher layers to ensure reliability

15
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 15
Transport Layer

● Send variable-length data from any point to any other point


○ Relies on network layer to send packets
● Useful abstractions
○ Reliability: Transmit data reliably, in order
○ Ports: Provide multiple “addresses” per real IP address
● Examples
○ TCP: Provides reliability and ports
○ UDP: Provides ports, but no reliability

16
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 16
Transport Layer

● Provides resilience to
○ Data corruption
■ Payload checksum
○ Data loss
■ Sequence numbers, timeouts + retransmits
○ Out-of-order delivery
■ Sequence numbers
○ Congestion
■ Flow control, AIMD
● UDP is suitable when error checking is not necessary or performed in the
application
○ Avoids overhead of such processing at the network level
○ Time-sensitive applications often use UDP

17
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 17
Application Layer

● Highest level of abstraction


● The actual application that the users use
● Uses transport layer to send data from one point to another

● As we move to lower layers, we wrap additional headers around the


message
● As we move to higher layers, we remove the headers around the
message
● When sending a message we go from the highest to the lowest layer
● When receiving a message we go from the lowest to highest layer

18
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 18
Naming and Identification

● IP addresses vs. readable host names


○ Humans are not good at remembering numbers ([Link])
○ Globally unique (but can correspond to multiple hosts, e.g., [Link])
● Naming system translates readable host names to physical address
○ DNS translates name to IP address (e.g.,[Link])
○ Address reflects location in the network
● Common authentication problem
○ IP-based authentication/identification can be defeated by IP address spoofing

19
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 19
DNS

● The Internet maintains a mapping between IP addresses and


domain names in a worldwide distributed database called DNS
● Conceptually, programmers can view the DNS database as a
collection of millions of host entries.
○ Each host entry defines the mapping between a set of domain names
and IP addresses.
○ In a mathematical sense, a host entry is an equivalence class of domain
names and IP addresses.

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 20


Client-Server Programming

● Most network applications are based on the client-server model:


○ A server process and one or more client processes
○ Server manages some resource
○ Server provides service by manipulating resource for clients
○ Server activated by request from client
● Clients and servers most often communicate by sending streams of
bytes over TCP connections. Each connection is:
○ Point-to-point: connects a pair of processes.
○ Full-duplex: data can flow in both directions at the same time,
○ Reliable: stream of bytes sent by the source is eventually received by
the destination in the same order it was sent.
● A socket is an endpoint of a connection
○ Socket address is an IPaddress:port pair

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 21


Ports

● Popular services have permanently assigned well-known ports and


corresponding well-known service names:
○ ftp servers: ftp
○ ssh servers: ssh
○ email servers: smtp
○ Unencrypted Web servers: http
○ Encrypted Web: https
● Ports assigned by the kernel on the client side in an adhoc fashion
are ephemeral ports

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 22


Ports

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 23


Sockets Interface

● Set of system-level functions used in conjunction with Unix I/O to


build network applications.
● Created in the early 80’s as part of the original Berkeley
distribution of Unix that contained an early version of the Internet
protocols.
● Available on all modern systems
○ Unix variants, Windows, OS X, IOS, Android, ARM

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 24


Sockets

● What is a socket?
○ To the kernel, a socket is an endpoint of communication
○ To an application, a socket is a file descriptor that lets the application
read/write from/to the network
● Using the FD abstraction lets you reuse code & interfaces
○ Clients and servers communicate with each other by reading from and
writing to socket descriptors
● The main distinction between regular file I/O and socket I/O is
how the application “opens” the socket descriptors

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 25


Socket Programming

● Echo server and client


● Server
○ Accepts connection request
○ Repeats back lines as they are typed
● Client
○ Requests connection to server
○ Repeatedly:
■ Read line from terminal
■ Send to server
■ Read reply from server
■ Print line to terminal

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 26


2. Start client 1. Start server
Client Server

open_listen
fd
open_client
fd

Connection Await connection


request request from client
accept

terminal 3. Exchange
Client / read socket read data
socket write
Server
socket read
Session socket
terminal
write
write

EOF
close socket read

5. Drop client
4. Disconnect client
close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 27
Start client Start server
Client Server
getaddrinfo getaddrinfo

socket socket
open_listenfd
open_clientfd bind

listen
Connection
request
connect accept

rio_readlin
Client / rio_writen
eb
Server
Session rio_readline
Await connection
rio_writen request from
b
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 28
Echo Client-Server
int main(int argc, char **argv)
{
int clientfd;
char *host, *port, buf[MAXLINE];
rio_t rio;
host = argv[1];
port = argv[2];
clientfd = Open_clientfd(host, port);
Rio_readinitb(&rio, clientfd);
while (Fgets(buf, MAXLINE, stdin) != NULL) {
Rio_writen(clientfd, buf, strlen(buf));
Rio_readlineb(&rio, buf, MAXLINE);
Fputs(buf, stdout);
}
Close(clientfd);
exit(0);
}

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 29


Generic Socket Address
⬛ Generic socket address:
▪ For address arguments to connect, bind, and accept

struct sockaddr {
uint16_t sa_family; /* Protocol family */
char sa_data[14]; /* Address data. */
};

sa_family
Family Specific

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 30


Socket Address Structures
⬛ Internet (IPv4) specific socket address:
▪ Must cast (struct sockaddr_in *) to (struct sockaddr *)
for functions that take socket address arguments.

struct sockaddr_in {
uint16_t sin_family; /* Protocol family (always AF_INET) */
uint16_t sin_port; /* Port num in network byte order */
struct in_addr sin_addr; /* IP addr in network byte order */
unsigned char sin_zero[8]; /* Pad to sizeof(struct sockaddr) */
};

sin_port sin_addr
AF_INET 0 0 0 0 0 0 0 0
sa_family
sin_family
Family Specific

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 31


getaddrinfo
⬛ getaddrinfo converts string representations of hostnames, host
addresses, ports, service names to socket address structures
addrinfo structs
SA list result

ai_canonna Socket address structs


me
ai_addr
ai_next

NULL
ai_addr
ai_next

NULL
ai_addr
NULL

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 32


Start client Start server
Client Server
getaddrinfo getaddrinfo
SA list SA list
socket socket
open_listenfd
open_clientfd bind

listen
Connection
request
connect accept

rio_readlin
Client / rio_writen
eb
Server
Session rio_readline
Await connection
rio_writen request from
b
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 33
Sockets Interface: socket
⬛ Clients and servers use the socket function to create a
socket descriptor:
int socket(int domain, int type, int protocol)

⬛ Example:
int clientfd = socket(AF_INET, SOCK_STREAM, 0); Protocol specific!

Indicates that we are using Indicates that the socket


32-bit IPV4 addresses will be the end point of a
reliable (TCP) connection
⬛ Example:
int clientfd = socket(ai->ai_family, ai->ai_socktype,
ai->ai_protocol);
Use getaddrinfo and you don’t have
to know or care which protocol!
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 34
Start server
Client Server Sockets
getaddrinfo getaddrinfo Interface
SA list SA list
socket socket
clientfd listenfd open_listenfd
open_clientfd bind

listen
Connection
request
connect accept

rio_readlin
Client / rio_writen
eb
Server
Session rio_readline
Await connection
rio_writen request from
b
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 35
Sockets Interface: bind
⬛ A server uses bind to ask the kernel to associate the
server’s socket address with a socket descriptor:
int bind(int sockfd, SA *addr, socklen_t addrlen);

Our convention: typedef struct sockaddr SA;


⬛ Process can read bytes that arrive on the connection whose
endpoint is addr by reading from descriptor sockfd
⬛ Similarly, writes to sockfd are transferred along
connection whose endpoint is addr
⬛ Best practice is to use getaddrinfo to supply the
arguments addr and addrlen.

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 36


Client Server Sockets
getaddrinfo getaddrinfo Interface
SA list SA list
socket socket
clientfd listenfd open_listenfd
open_clientfd bind
listenfd <-> SA
listen
Connection
request
connect accept

rio_readlin
Client / rio_writen
eb
Server
Session rio_readline
Await connection
rio_writen request from
b
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 37
Sockets Interface: listen
⬛ Kernel assumes that descriptor from socket function is an
active socket that will be on the client end
⬛ A server calls the listen function to tell the kernel that a
descriptor will be used by a server rather than a client:
int listen(int sockfd, int backlog);

⬛ Converts sockfd from an active socket to a listening


socket that can accept connection requests from clients.

⬛ backlog is a hint about the number of outstanding


connection requests that the kernel should queue up
before starting to refuse requests (128-ish by default)

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 38


Client Server Sockets
getaddrinfo getaddrinfo Interface
SA list SA list
socket socket
clientfd listenfd open_listenfd
open_clientfd bind
listenfd <-> SA
listen
Connection listening listenfd
request
connect accept

rio_readlin
Client / rio_writen
eb
Server
Session rio_readline
Await connection
rio_writen request from
b
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 39
Sockets Interface: accept
⬛ Servers wait for connection requests from clients by
calling accept:
int accept(int listenfd, SA *addr, int *addrlen);

⬛ Waits for connection request to arrive on the connection


bound to listenfd, then fills in client’s socket address
in addr and size of the socket address in addrlen.

⬛ Returns a connected descriptor connfd that can be used


to communicate with the client via Unix I/O routines.

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 40


Client Server Sockets
getaddrinfo getaddrinfo Interface
SA list SA list
socket socket
clientfd listenfd open_listenfd
open_clientfd bind
listenfd <-> SA
listen
Connection listening listenfd
request
connect accept

rio_readlin
rio_writen
Client / eb
Server
Await connection
Session rio_readline
rio_writen
b request from
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 41
Sockets Interface: connect
⬛ A client establishes a connection with a server by calling
connect:
int connect(int clientfd, SA *addr, socklen_t addrlen);

⬛ Attempts to establish a connection with server at socket


address addr
▪ If successful, then clientfd is now ready for reading and writing.
▪ Resulting connection is characterized by socket pair
(x:y, addr.sin_addr:addr.sin_port)
▪ x is client address
▪ y is ephemeral port that uniquely identifies client process on
client host
⬛ Best practice is to use getaddrinfo to supply the
arguments addr and addrlen.
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 42
connect/accept Illustrated
listenfd
1. Server blocks in accept,
Client Server waiting for connection request
clientfd on listening descriptor
listenfd

Connection
listenfd
request 2. Client makes connection request by
Client Server calling and blocking in connect
clientfd

listenfd
3. Server returns connfd from
Client Server accept. Client returns from connect.
clientfd connfd
Connection is now established between
clientfd and connfd

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 43


Connected vs. Listening Descriptors
⬛ Listening descriptor
▪ End point for client connection requests
▪ Created once and exists for lifetime of the server

⬛ Connected descriptor
▪ End point of the connection between client and server
▪ A new descriptor is created each time the server accepts a
connection request from a client
▪ Exists only as long as it takes to service client

⬛ Why the distinction?


▪ Allows for concurrent servers that can communicate over many
client connections simultaneously
▪ E.g., Each time we receive a new request, we fork a child to
handle the request
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 44
Client Server
getaddrinfo getaddrinfo
SA list SA list
socket socket
clientfd listenfd open_listenfd
open_clientfd bind
listenfd <-> SA
listen
Connection listening listenfd
request
connect accept
connected (to SA) clientfd connected connfd
rio_readlin
rio_writen
Client / eb
Server
Await connection
Session rio_readline
rio_writen
b request from
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 45
Client Server
getaddrinfo getaddrinfo

socket socket
open_listenfd
open_clientfd bind

listen
Connection
request
connect accept

rio_readlin
Client / rio_writen
eb
Server
Session rio_readline
Await connection
rio_writen request from
b
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 46
Sockets Helper: open_clientfd
⬛ Establish a connection with a server
int open_clientfd(char *hostname, char *port) {
int clientfd;
struct addrinfo hints, *listp, *p;

/* Get a list of potential server addresses */


memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM; /* Open a connection */
hints.ai_flags = AI_NUMERICSERV; /* …using numeric port arg. */
hints.ai_flags |= AI_ADDRCONFIG; /* Recommended for connections */
Getaddrinfo(hostname, port, &hints, &listp);
csapp.c

AI_ADDRCONFIG means “use whichever of IPv4 and IPv6 works


on this computer”. Good practice for clients, not for servers.

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 47


getaddrinfo
addrinfo structs
result

ai_canonna Socket address structs


me
ai_addr
ai_next

NULL
ai_addr
ai_next

NULL
ai_addr
NULL

⬛ Clients: walk this list, trying each socket address in turn, until the calls to
socket and connect succeed.
⬛ Servers: walk the list calling socket, listen, bind for all addresses, then use
select to accept connections on any of them (beyond our scope)
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 48
Sockets Helper: open_clientfd (cont)
/* Walk the list for one that we can successfully connect to */
for (p = listp; p; p = p->ai_next) {
/* Create a socket descriptor */
if ((clientfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) < 0)
continue; /* Socket failed, try the next */

/* Connect to the server */


if (connect(clientfd, p->ai_addr, p->ai_addrlen) != -1)
break; /* Success */
Close(clientfd); /* Connect failed, try another */
}

/* Clean up */
Freeaddrinfo(listp);
if (!p) /* All connects failed */
return -1;
else /* The last connect succeeded */
return clientfd;
} csapp.c
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 49
Client Server
getaddrinfo getaddrinfo

socket socket
open_listenfd
open_clientfd bind

listen
Connection
request
connect accept

rio_readlin
Client / rio_writen
eb
Server
Session rio_readline
Await connection
rio_writen request from
b
next client
EOF rio_readlin
close
eb

close
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 50
Sockets Helper: open_listenfd
⬛ Create a listening descriptor that can be used to accept
connection requests from clients.
int open_listenfd(char *port)
{
struct addrinfo hints, *listp, *p;
int listenfd, optval=1;

/* Get a list of potential server addresses */


memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM; /* Accept connect. */
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; /* …on any IP addr */
hints.ai_flags |= AI_NUMERICSERV; /* …using port no. */
Getaddrinfo(NULL, port, &hints, &listp);

csapp.c

AI_PASSIVE means “I plan to listen on this socket.”


AI_ADDRCONFIG normally not used for servers, but we use it for convenience
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 51
Sockets Helper: open_listenfd (cont)
/* Walk the list for one that we can bind to */
for (p = listp; p; p = p->ai_next) {
/* Create a socket descriptor */
if ((listenfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) < 0)
continue; /* Socket failed, try the next */

/* Eliminates "Address already in use" error from bind */


Setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int));

/* Bind the descriptor to the address */


if (bind(listenfd, p->ai_addr, p->ai_addrlen) == 0)
break; /* Success */
Close(listenfd); /* Bind failed, try the next */
} csapp.c

A production server would not break out of the loop on the first success.
We do that for simplicity only.

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 52


Sockets Helper: open_listenfd (cont)
/* Clean up */
Freeaddrinfo(listp);
if (!p) /* No address worked */
return -1;

/* Make it a listening socket ready to accept conn. requests */


if (listen(listenfd, LISTENQ) < 0) {
Close(listenfd);
return -1;
}
return listenfd;
} csapp.c

⬛ Key point: open_clientfd and open_listenfd are


both independent of any particular version of IP.
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 53
Testing Servers Using telnet
⬛ The telnet program is invaluable for testing servers
that transmit ASCII strings over Internet connections
▪ Our simple echo server
▪ Web servers
▪ Mail servers

⬛ Usage:
▪ linux> telnet <host> <portnumber>
▪ Creates a connection with a server running on <host> and
listening on port <portnumber>

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 54


Web Server Basics

⬛ Clients and servers communicate HTTP request


using the HyperText Transfer Web
Web
Protocol (HTTP) client
server
(browser)
▪ Client and server establish TCP
HTTP response
connection
(content)
▪ Client requests content
▪ Server responds with requested
content HTTP Web content
▪ Client and server close connection
(eventually) TCP Streams
⬛ Current version is HTTP/2.0
but HTTP/1.1 widely used still IP Datagrams
▪ RFC 2616, June, 1999.

[Link]

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 55


Web Content
⬛ Web servers return content to clients
▪ content: a sequence of bytes with an associated MIME (Multipurpose
Internet Mail Extensions) type

⬛ Example MIME types


▪ text/html HTML document
▪ text/plainUnformatted text
▪ image/gif Binary image encoded in GIF format
▪ image/png Binary image encoded in PNG format
▪ image/jpegBinary image encoded in JPEG format

You can find the complete list of MIME types at:


[Link]
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 56
Static and Dynamic Content
⬛ The content returned in HTTP responses can be either static or
dynamic
▪ Static content: content stored in files and retrieved in response to an HTTP
request
▪ Examples: HTML files, images, audio clips, Javascript programs
▪ Request identifies which content file
▪ Dynamic content: content produced on-the-fly in response to an HTTP
request
▪ Example: content produced by a program executed by the server on
behalf of the client
▪ Request identifies file containing executable code

⬛ Web content associated with a file that is managed by the server

Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 57


URLs and how clients and servers use them
⬛ Unique name for a file: URL (Universal Resource Locator)
⬛ Example URL: [Link]
⬛ Clients use prefix ([Link] to infer:
▪ What kind (protocol) of server to contact (HTTP)
▪ Where the server is ([Link])
▪ What port it is listening on (80)
⬛ Servers use suffix (/[Link]) to:
▪ Determine if request is for static or dynamic content.

No hard and fast rules for this
▪ One convention: executables reside in cgi-bin directory
▪ Find file on file system
▪ Initial “/” in suffix denotes home directory for requested content.
▪ Minimal suffix is “/”, which server expands to configured default
filename (usually, [Link])
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 58
HTTP Request Example
GET / HTTP/1.1 Client: request line
Host: [Link] Client: required HTTP/1.1 header
Client: blank line terminates headers

⬛ HTTP standard requires that each text line end with “\r\n”
⬛ Blank line (“\r\n”) terminates request and response headers 59
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
HTTP Requests
⬛ HTTP request is a request line, followed by zero or more
request headers

⬛ Request line: <method> <uri> <version>


▪ <method> is one of GET, POST, OPTIONS, HEAD, PUT,
DELETE, or TRACE
▪ <uri> is typically URL for proxies, URL suffix for servers
▪ A URL is a type of URI (Uniform Resource Identifier)
▪ See [Link]
▪ <version> is HTTP version of request (HTTP/1.0 or HTTP/1.1)

⬛ Request headers: <header name>: <header data>


▪ Provide additional information to the server
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 60
HTTP Responses
⬛ HTTP response is a response line followed by zero or more
response headers, possibly followed by content, with blank line
(“\r\n”) separating headers from content.

⬛ Response line:
<version> <status code> <status msg>
▪ <version> is HTTP version of the response
▪ <status code> is numeric status
▪ <status msg> is corresponding English text
▪ 200 OK Request was handled without error
▪ 301 Moved Provide alternate URL
▪ 404 Not foundServer couldn’t find the file
⬛ Response headers: <header name>: <header data>
▪ Provide additional information about response
▪ Content-Type: MIME type of content in response body
▪ Content-Length: Length of content in response body
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 61

You might also like