Download Networking - Rice University

Document related concepts

Net bias wikipedia , lookup

Parallel port wikipedia , lookup

Server Message Block wikipedia , lookup

Wake-on-LAN wikipedia , lookup

Piggybacking (Internet access) wikipedia , lookup

Distributed firewall wikipedia , lookup

Recursive InterNetwork Architecture (RINA) wikipedia , lookup

AppleTalk wikipedia , lookup

Dynamic Host Configuration Protocol wikipedia , lookup

Cracking of wireless networks wikipedia , lookup

Remote Desktop Services wikipedia , lookup

Real-Time Messaging Protocol wikipedia , lookup

Zero-configuration networking wikipedia , lookup

Lag wikipedia , lookup

Hypertext Transfer Protocol wikipedia , lookup

Transcript
Networking
Alan L. Cox
[email protected]
T. S. Eugene Ng
[email protected]
Some slides adapted from CMU 15.213 slides
Objectives
Be exposed to the basic underpinnings of the
Internet
Be able to use network socket interfaces
effectively
Be exposed to the basic underpinnings of the
World Wide Web
Cox & Ng
Networking
2
The 2004 A. M. Turing Award Goes
to...
Cox & Ng
Networking
3
The 2004 A. M. Turing Award Goes
to...
Bob Kahn
Vint Cerf
"For pioneering work on internetworking, including
the design and implementation of the Internet's
basic communications protocols, TCP/IP, and for
inspired leadership in networking."
The only Turing Award given to-date to recognize
work in computer networking
Cox & Ng
Networking
4
But at the Same Time...
Daily, e.g. 110 attacks from
China; 26 attacks from USA
2/24/2008 YouTube traffic
mis-routed to Pakistan
Q2/2008 1000s of Netherlands
DSL customers lost service due to
network configuration
error (Brazil) black-holed
11/10/2008 CTBC
all Internet traffic in some parts of Brazil
2/16/2009 Supro (Czech) routing messages
triggered a Cisco router bug world-wide
5/2009 AfNOG (Africa) routing messages
triggered buffer overflow in open-source
routing software Quagga world-wide
Source: Akamai Technologies, Inc.
Cox & Ng
Networking
5
Telephony
Interactive telecommunication between
people
Analog voice
 Transmitter/receiver continuously in contact
with electronic circuit
 Electric current varies with acoustic pressure
Analog/Continuous Signal
Over electrical circuits
Cox & Ng
Networking
6
Telephony Milestones
1876: Alexander Bell invented telephone
1878: Public switches installed at New Haven and San
Francisco, public switched telephone network is born
 People can talk without being on the same
wire!
Without Switch
Cox & Ng
With Switch
Networking
7
Telephony Milestones
1878: First telephone directory; White House line
1881: Insulated, balanced twisted pair as local
loop
1885: AT&T formed
1892: First automatic commercial telephone
switch
1903: 3 million telephones in U.S.
1915: First transcontinental telephone line
1927: First commercial transatlantic commercial
service
Cox & Ng
Networking
8
Telephony Milestones
1937: Multiplexing introduced for inter-city calls
 One link carries multiple conversations
With Multiplexing
Without Multiplexing
Cox & Ng
Networking
9
Data or Computer Networks
Networks designed for computers to computers
or devices
 vs. communication between human beings
Digital information
 vs. analog voice
Digital/Discrete Signal
Not a continuous stream of bits, rather,
discrete “packets” with lots of silence in
between
 Dedicated circuit hugely inefficient
 Packet switching invented
Cox & Ng
Networking
10
Major Internet Milestones
1960-1964 Basic concept of “packet switching” was
independently developed by Baran (RAND),
Kleinrock (MIT)
 AT&T insisted that packet switching would never
work!
1965 First time two computers talked to each other
using packets (Roberts, MIT; Marill, SDC)
dial-up
MIT TX-2
Cox & Ng
SDC Q32
Networking
11
Major Internet Milestones
1968 BBN group proposed to use Honeywell 516
mini-computers for the Interface Message
Processors (i.e. packet switches)
1969 The first ARPANET message transmitted
between UCLA (Kleinrock) and SRI (Engelbart)
 We sent an “L”, did you get the “L”? Yep!
 We sent an “O”, did you get the “O”? Yep!
 We sent a “G”, did you get the “G”?
Crash!
Cox & Ng
Networking
12
Major Internet Milestones
• 1970 First packet radio network ALOHANET
(Abramson, U Hawaii)
• 1973 Ethernet invented (Metcalfe, Xerox PARC)
• Why is it called the “Inter-net”?
• 1974 “A protocol for Packet Network Interconnection”
published by Cerf and Kahn
– First internetworking protocol TCP
– This paper was cited for their Turing Award
• 1977 First TCP operation over ARPANET, Packet
Radio Net, and SATNET
• 1985 NSF commissions NSFNET backbone
• 1991 NSF opens Internet to commercial use
Cox & Ng
Networking
13
Internet Hourglass Architecture
Email, Web, ssh,...
TCP, UDP, …
IP
Ethernet, WiFi,
3G, bluetooth,...
Cox & Ng
Networking
14
A Client-Server Transaction
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
1. Client sends request
Client
process
4. Client
handles
response
Server
process
3. Server sends response
Resource
2. Server
handles
request
Note: clients and servers are processes running on hosts
(can be the same or different hosts)
Cox & Ng
Networking
15
Network Hardware
register file
CPU chip
ALU
system bus
memory bus
main
memory
I/O
bridge
Bus Interface
Expansion slots
I/O bus
USB
controller
mouse keyboard
Cox & Ng
graphics
adapter
disk
controller
network
adapter
disk
network
monitor
Networking
16
Computer Networks
A network is a hierarchical system of boxes
and wires organized by geographical
proximity
 Cluster network spans cluster or machine room
• Switched Ethernet, Infiniband, Myrinet, …
 LAN (local area network) spans a building or
campus
• Ethernet is most prominent example
 WAN (wide-area network) spans very long distance
• A high-speed point-to-point link
• Leased line or SONET/SDH circuit, or MPLS/ATM
circuit
An internetwork (internet) is an
interconnected set of networks
 The Global IP Internet (uppercase “I”) is the most
famous example of an internet (lowercase “i”)
Cox & Ng
Networking
17
Lowest Level: Ethernet Segment
Ethernet segment consists of a collection of hosts
connected by wires (twisted pairs) to a hub
host
host
100 Mb/s
host
100 Mb/s
hub
ports
Operation
 Each Ethernet adapter has a unique 48-bit address
 Hosts send bits to any other host in chunks called frames
 Hub slavishly copies each bit from each port to every
other port
• Every host sees every bit
 Note: Hubs are largely obsolete
• Bridges (switches, routers) became cheap enough to replace
them (don’t broadcast all traffic)
Cox & Ng
Networking
18
Next Level: Bridged Ethernet Segment
Spans room, building, or campus
Bridges cleverly learn which hosts are
reachable from which ports and then
selectively copy frames from port to port
host
host
host
host
bridge
hub
100 Mb/s
hub
100 Mb/s
1-10 Gb/s
host
host
Cox & Ng
1 Gb/s
1 Gb/s
host
bridge
1 Gb/s
host
Networking
host
host
bridge
host
host
19
Conceptual View of LANs
For simplicity, hubs, bridges, and wires are
often shown as a collection of hosts attached
to a single wire:
host
Cox & Ng
host ...
host
Networking
20
Next Level: internets
Multiple incompatible LANs can be physically
connected by specialized computers called
routers
The connected networks are called an internet
host
host ...
host
host
host ...
LAN 1
host
LAN 2
router
WAN
router
WAN
router
LAN 1 and LAN 2 might be completely different,
totally incompatible LANs (e.g., Ethernet and WiFi,
802.11*, T1-links, DSL, …)
Cox & Ng
Networking
21
The Internet Circa 1986
In 1986, the Internet consisted of one backbone
(NSFNET) that connected 13 sites via 45 Mbps T3 links
 Merit (Univ of Mich)
 BARRNet (Palo Alto)
 NCSA (Illinois)
 MidNet (Lincoln, NE)
 Cornell Theory Center
 WestNet (Salt Lake City)
 Pittsburgh
 NorthwestNet (Seattle)
Supercomputing Center
 San Diego
Supercomputing Center
 John von Neumann
Center (Princeton)
 SESQUINET (Rice)
 SURANET (Georgia
Tech)
Connecting to the Internet involved connecting one of
your routers to a router at a backbone site, or to a
regional network that was already connected to the
backbone
Cox & Ng
Networking
22
NSFNET Internet Backbone
source: www.eef.org
Cox & Ng
Networking
23
After NSFNET
Early 90s
 Commercial enterprises began building their own
high-speed backbones
 Backbone would connect to NSFNET, sell access to
companies, ISPs, and individuals
1995
 NSFNET decommissioned
 NSF fostered the creation of network access points
(NAPs) to interconnect the commercial backbones
Cox & Ng
Networking
24
Current Internet Architecture
Cox & Ng
Networking
25
Level 3 Backbone
Cox & Ng
Networking
26
AT&T Backbone
Cox & Ng
Networking
27
Submarine Cabling
Cox & Ng
Networking
28
The Notion of an internet Protocol
How is it possible to send bits across
incompatible LANs and WANs?
Solution: protocol software running on each
host and router smoothes out the differences
between the different networks
Implements an internet protocol (i.e., set of
rules) that governs how hosts and routers
should cooperate when they transfer data
from network to network
 TCP/IP is the protocol for the global IP Internet
Cox & Ng
Networking
29
What Does an internet Protocol Do?
1. Provides a naming scheme
 An internet protocol defines a uniform format for
host addresses
 Each host (and router) is assigned at least one of
these internet addresses that uniquely identifies it
2. Provides a delivery mechanism
 An internet protocol defines a standard transfer
unit (packet)
 Packet consists of header and payload
• Header: contains info such as packet size, source and
destination addresses
• Payload: contains data bits sent from source host
Cox & Ng
Networking
30
Transferring Data Over an internet
(1)
client
server
protocol
software
data
data
LAN1
adapter
PH FH1
(4)
Router
LAN1
adapter
LAN1
data
(8)
data
(7)
data
PH FH2
(6)
data
PH FH2
protocol
software
PH FH1
LAN1 frame
(3)
Host B
data
internet packet
(2)
Host A
LAN2
adapter
PH FH1
LAN2
adapter
LAN2 frame
data
LAN2
PH FH2 (5)
protocol
software
Cox & Ng
Networking
31
Other Issues
We are glossing over a number of important
questions:
 What if different networks have different maximum
frame sizes? (segmentation)
 How do routers know where to forward frames?
 How are routers informed when the network
topology changes?
 What if packets get lost?
We’ll leave the discussion of these question to
computer networking classes (COMP 429)
Cox & Ng
Networking
32
Global IP Internet
Based on the TCP/IP protocol family
 IP (Internet protocol) :
• Provides basic naming scheme and unreliable delivery
capability of packets (datagrams) from host-to-host
 UDP (Unreliable Datagram Protocol)
• Uses IP to provide unreliable datagram delivery from
process-to-process
 TCP (Transmission Control Protocol)
• Uses IP to provide reliable byte streams from
process-to-process over connections
Accessed via a mix of Unix file I/O and
functions from the sockets interface
Cox & Ng
Networking
33
Organization of an Internet Application
Internet client
Internet server
Client
User code
Server
TCP/IP
Kernel code
TCP/IP
Sockets interface
(system calls)
Hardware interface
(interrupts)
Network
adapter
Hardware
and firmware
Network
adapter
Global IP Internet
Cox & Ng
Networking
34
A Programmer’s View of the Internet
Hosts are mapped to a set of 32-bit IP
addresses
 128.42.1.125 (4 * 8 bits)
A set of identifiers called Internet domain
names are mapped to the set of IP addresses
for convenience
 www.cs.rice.edu is mapped to 128.42.1.125
A process on one Internet host can
communicate with a process on another
Internet host over a connection
Cox & Ng
Networking
35
IP Addresses
32-bit IP addresses are stored in an IP
address struct
 IP addresses are always stored in memory in
network byte order (big-endian byte order)
 True in general for any integer transferred in a
packet header from one machine to another
• E.g., the port number used to identify an Internet
connection
/* Internet address structure */
struct in_addr {
unsigned int s_addr; /* network byte order (big-endian) */
};
Handy network byte-order conversion functions:
htonl: convert long int from host to network byte order
htons: convert short int from host to network byte order
ntohl: convert long int from network to host byte order
ntohs: convert short int from network to host byte order
Cox & Ng
Networking
36
Dotted Decimal Notation
By convention, each byte in a 32-bit IP
address is represented by its decimal value
and separated by a period
• IP address 0x8002C2F2 = 128.2.194.242
Functions for converting between binary IP
addresses and dotted decimal strings:
 inet_aton: converts a dotted decimal string to an
IP address in network byte order
 inet_ntoa: converts an IP address in network by
order to its corresponding dotted decimal string
 “n” denotes network representation, “a” denotes
application representation
Cox & Ng
Networking
37
IP Address Structure
IP (V4) Address space divided into classes:
0123
Class A 0 Net ID
Class B 1 0
Class C 1 1 0
Class D 1 1 1 0
Class E 1 1 1 1
8
16
24
31
Host ID
Net ID
Host ID
Net ID
Host ID
Multicast address
Reserved for experiments
Special Addresses for routers and gateways
(all 0/1’s)
Loop-back address: 127.0.0.1
Unrouted (private) IP addresses:
 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
Dynamic IP addresses (DHCP)
Cox & Ng
Networking
38
Internet Domain Names
unnamed root
.net
.edu
mit
rice
clear
crystal
128.42.151.14
128.42.151.13
.com
berkeley
cs
bell
Cox & Ng
.gov
amazon
www
72.21.210.11
Networking
First-level domain names
Second-level domain names
Third-level domain names
39
Domain Naming System (DNS)
The Internet maintains a mapping between IP
addresses and domain names in a huge worldwide
distributed database called DNS
 Conceptually, programmers can view the DNS database
as a collection of millions of host entry structures:
/* DNS host entry structure
struct hostent {
char
*h_name;
/*
char
**h_aliases;
/*
int
h_addrtype;
/*
int
h_length;
/*
char
**h_addr_list; /*
};
*/
official domain name of host */
null-terminated array of domain names */
host address type (AF_INET) */
length of an address, in bytes */
null-terminated array of in_addr structs */
Functions for retrieving host entries from DNS:
 gethostbyname: query key is a DNS domain name
 gethostbyaddr: query key is an IP address
Cox & Ng
Networking
40
Properties of DNS Host Entries
Each host entry is an equivalence class of domain
names and IP addresses
Each host has a locally defined domain name localhost
which always maps to the loopback address 127.0.0.1
Different kinds of mappings are possible:
 Simple case: 1 domain name maps to one IP address:
• forest.owlnet.rice.edu maps to 10.130.195.71
 Multiple domain names mapped to the same IP address:
• www.cs.rice.edu, ececs.rice.edu, and bianca.cs.rice.edu all
map to 128.42.1.125
 Multiple domain names mapped to multiple IP addresses:
• aol.com and www.aol.com map to multiple IP addresses
 Some valid domain names don’t map to any IP address:
• for example: clear.rice.edu
Cox & Ng
Networking
41
A Program That Queries DNS
int main(int argc, char **argv) { /* argv[1] is a domain name */
char **pp;
/* or dotted decimal IP addr */
struct in_addr addr;
struct hostent *hostp;
if (inet_aton(argv[1], &addr) != 0)
hostp = Gethostbyaddr((const char *)&addr, sizeof(addr),
AF_INET);
else
hostp = Gethostbyname(argv[1]);
printf("official hostname: %s\n", hostp->h_name);
for (pp = hostp->h_aliases; *pp != NULL; pp++)
printf("alias: %s\n", *pp);
for (pp = hostp->h_addr_list; *pp != NULL; pp++) {
addr.s_addr = *((unsigned int *)*pp);
printf("address: %s\n", inet_ntoa(addr));
}
}
Cox & Ng
Networking
42
Querying DNS
Domain Information Groper (dig) provides a
scriptable command line interface to DNS
 Available on CLEAR
 Lots of web interfaces (google “domain
information groper”)
unix> dig +short bianca.cs.rice.edu
128.42.1.125
unix> dig +short -x 128.42.1.125
bianca.cs.rice.edu.
unix> dig +short google.com
72.14.207.99
64.233.187.99
64.233.167.99
unix> dig +short -x 64.233.167.99
py-in-f99.google.com.
Cox & Ng
Networking
43
Internet Connections
Clients and servers communicate by sending streams of
bytes over connections:
 Point-to-point, full-duplex (2-way communication), and
reliable
A socket is an endpoint of a connection
 Socket address is an IP address, port pair
A port is a 16-bit integer that identifies a process:
 Ephemeral port: Assigned automatically on client when
client makes a connection request
 Well-known port: Associated with some service provided
by a server (e.g., port 80 is associated with Web servers)
A connection is uniquely identified by the socket
addresses of its endpoints (socket pair)
 (cliaddr:cliport, servaddr:servport)
Cox & Ng
Networking
44
Putting it all Together:
Anatomy of an Internet Connection
Client socket address
128.2.194.242:51213
Client
Server socket address
208.216.181.15:80
Connection socket pair
(128.2.194.242:51213, 208.216.181.15:80)
Client host address
128.2.194.242
Cox & Ng
Server
(port 80)
Server host address
208.216.181.15
Networking
45
Clients
Examples of client programs
 Web browsers, ftp, telnet, ssh
How does a client find the server?
 The IP address in the server socket address
identifies the host (more precisely, an adapter on
the host)
 The (well-known) port in the server socket address
identifies the service, and thus implicitly identifies
the server process that performs that service
 Examples of well known ports
•
•
•
•
Cox & Ng
Port
Port
Port
Port
7: Echo server
23: Telnet server
25: Mail server
80: Web server
Networking
46
Using Ports to Identify Services
Server host 128.2.194.242
Client host
Service request for
128.2.194.242:80
(i.e., the Web server)
Client
Web server
(port 80)
Kernel
Echo server
(port 7)
Client
Service request for
128.2.194.242:7
(i.e., the echo server)
Web server
(port 80)
Kernel
Echo server
(port 7)
Cox & Ng
Networking
47
Servers
Servers are long-running processes
(daemons)
 Created at boot-time (typically) by the init process
(process 1)
 Run continuously until the machine is turned off
Each server waits for requests to arrive on a
well-known port associated with a particular
service




Port
Port
Port
Port
7: echo server
23: telnet server
25: mail server
80: HTTP server
A machine that runs a server process is also
often referred to as a “server”
Cox & Ng
Networking
48
Server Examples
Web server (port 80)
 Resource: files/compute cycles (CGI programs)
 Service: retrieves files and runs CGI programs on
behalf of the client
FTP server (20, 21)
 Resource: files
See /etc/services for a
comprehensive list of the services
available on a UNIX machine
 Service: stores and retrieve files
Telnet server (23)
 Resource: terminal
 Service: proxies a terminal on the server machine
Mail server (25)
 Resource: email “spool” file
 Service: stores mail messages in spool file
Cox & Ng
Networking
49
Sockets Interface
Created in the early 80’s as part of the original
Berkeley distribution of Unix that contained
an early version of the Internet protocols
Provides a user-level interface to the network
Underlying basis for all Internet applications
Based on client/server programming model
Cox & Ng
Networking
50
Overview of the Sockets Interface
Client
Server
socket
socket
bind
open_listenfd
open_clientfd
listen
connect
Connection
request
rio_writen
rio_readlineb
rio_readlineb
close
Cox & Ng
accept
rio_writen
EOF
rio_readlineb
Networking
close
Await connection
request from
next client
51
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
• Remember: all Unix I/O devices, including networks,
are modeled as files
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
Cox & Ng
Networking
52
Socket Address Structures
Generic socket address:
 Address for connect, bind, and accept
 C did not have generic (void *) pointers when the
sockets interface was designed
struct sockaddr {
unsigned short sa_family;
char
sa_data[14];
};
/* protocol family */
/* address data. */
Internet-specific socket address:
 Must cast (sockaddr_in *) to (sockaddr *)
struct sockaddr_in {
unsigned short sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
unsigned char
sin_zero[8];
};
Cox & Ng
/*
/*
/*
/*
address family (always AF_INET) */
port num in network byte order */
IP addr in network byte order */
pad to sizeof(struct sockaddr) */
Networking
53
Echo Client Main Routine
int main(int argc, char **argv) /* usage: ./echoclient host port */
{
int clientfd, port;
char *host, buf[MAXLINE];
rio_t rio;
host = argv[1];
port = atoi(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);
}
Cox & Ng
Networking
54
Echo Client: open_clientfd
int open_clientfd(char *hostname, int port) {
int clientfd;
This function opens a
struct hostent *hp;
connection from the client to
struct sockaddr_in serveraddr;
the server at hostname:port
if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1; /* check errno for cause of error */
/* Fill in the server's IP address and port */
if ((hp = gethostbyname(hostname)) == NULL)
return -2; /* check h_errno for cause of error */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)hp->h_addr,
(char *)&serveraddr.sin_addr.s_addr, hp->h_length);
serveraddr.sin_port = htons(port);
/* Establish a connection with the server */
if (connect(clientfd, (SA *) &serveraddr, sizeof(serveraddr)) < 0)
return -1;
return clientfd;
}
Cox & Ng
Networking
55
open_clientfd (socket)
socket creates a socket descriptor on the
client
 AF_INET: indicates that the socket is associated
with Internet protocols
 SOCK_STREAM: selects a reliable byte stream
connection
int clientfd;
/* socket descriptor */
if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1; /* check errno for cause of error */
... (more)
Cox & Ng
Networking
56
open_clientfd (gethostbyname)
The client then builds the server’s Internet
address
int clientfd;
/* socket descriptor */
struct hostent *hp;
/* DNS host entry */
struct sockaddr_in serveraddr; /* server’s IP address */
...
/* fill in the server's IP address and port */
if ((hp = gethostbyname(hostname)) == NULL)
return -2; /* check h_errno for cause of error */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)hp->h_addr,
(char *)&serveraddr.sin_addr.s_addr, hp->h_length);
serveraddr.sin_port = htons(port);
Cox & Ng
Networking
57
open_clientfd (connect)
Finally the client creates a connection with the
server
 Client process suspends (blocks) until the
connection is created
 After resuming, the client is ready to begin
exchanging messages with the server via Unix I/O
calls on descriptor clientfd
int clientfd;
/* socket descriptor */
struct sockaddr_in serveraddr;
/* server address */
typedef struct sockaddr SA;
/* generic sockaddr */
...
/* Establish a connection with the server */
if (connect(clientfd, (SA *)&serveraddr, sizeof(serveraddr)) < 0)
return -1;
return clientfd;
Cox & Ng
Networking
58
Echo Server: Main Routine
int main(int argc, char **argv) {
int listenfd, connfd, port, clientlen;
struct sockaddr_in clientaddr;
struct hostent *hp;
char *haddrp;
port = atoi(argv[1]); /* the server listens on the given port */
listenfd = open_listenfd(port);
while (1) {
clientlen = sizeof(clientaddr);
connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
hp = Gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr), AF_INET);
haddrp = inet_ntoa(clientaddr.sin_addr);
printf("server connected to %s (%s)\n", hp->h_name, haddrp);
echo(connfd);
Close(connfd);
}
}
Cox & Ng
Networking
59
Echo Server: open_listenfd
int open_listenfd(int port)
{
int listenfd, optval=1;
struct sockaddr_in serveraddr;
/* Create a socket descriptor */
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
/* Eliminates "Address already in use" error from bind. */
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int)) < 0)
return -1;
... (more)
Cox & Ng
Networking
60
Echo Server: open_listenfd (cont)
...
/* Listenfd will be an endpoint for all requests to port
on any IP address for this host */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
if (bind(listenfd, (SA *)&serveraddr, sizeof(serveraddr)) < 0)
return -1;
/* Make it a listening socket ready to accept
connection requests */
if (listen(listenfd, LISTENQ) < 0)
return -1;
return listenfd;
}
Cox & Ng
Networking
61
open_listenfd (socket)
socket creates a socket descriptor on the
server
 AF_INET: indicates that the socket is associated
with Internet protocols
 SOCK_STREAM: selects a reliable byte stream
connection
int listenfd; /* listening socket descriptor */
/* Create a socket descriptor */
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
Cox & Ng
Networking
62
open_listenfd (setsockopt)
The socket can be given some attributes
...
/* Eliminates "Address already in use" error from bind(). */
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int)) < 0)
return -1;
Handy trick that allows us to rerun the server
immediately after we kill it
 Otherwise we would have to wait about 30 secs
 Eliminates “Address already in use” error from
bind()
Strongly suggest you do this for all your
servers to simplify debugging
Cox & Ng
Networking
63
open_listenfd (init socket address)
Next, we initialize the socket with the server’s Internet
address (IP address and port)
struct sockaddr_in serveraddr; /* server's socket addr */
...
/* listenfd will be an endpoint for all requests to port
on any IP address for this host */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
IP address and port stored in network (big-endian)
byte order
 htonl() converts longs from host byte order to network
byte order
 htons() convers shorts from host byte order to network
byte order
Cox & Ng
Networking
64
open_listenfd (bind)
bind associates the socket with the socket
address we just created
int listenfd;
/* listening socket */
struct sockaddr_in serveraddr; /* server’s socket addr */
...
/* listenfd will be an endpoint for all requests to port
on any IP address for this host */
if (bind(listenfd, (SA *)&serveraddr, sizeof(serveraddr)) < 0)
return -1;
Cox & Ng
Networking
65
open_listenfd (listen)
listen indicates that this socket will accept
connection (connect) requests from clients
int listenfd; /* listening socket */
...
/* Make it a listening socket ready to accept connection requests */
if (listen(listenfd, LISTENQ) < 0)
return -1;
return listenfd;
}
We’re finally ready to enter the main server
loop that accepts and processes client
connection requests
Cox & Ng
Networking
66
Echo Server: Main Loop
The server loops endlessly, waiting for
connection requests, then reading input from
the client, and echoing the input back to the
client
main() {
/* create and configure the listening socket */
while(1) {
/* Accept(): wait for a connection request */
/* echo(): read and echo input lines from client til EOF */
/* Close(): close the connection */
}
}
Cox & Ng
Networking
67
Echo Server: accept
accept() blocks waiting for a connection request
int listenfd; /* listening descriptor */
int connfd;
/* connected descriptor */
struct sockaddr_in clientaddr;
int clientlen;
clientlen = sizeof(clientaddr);
connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
accept returns a connected descriptor (connfd) with the
same properties as the listening descriptor (listenfd)
 Returns when the connection between client and server
is created and ready for I/O transfers
 All I/O with the client will be done via the connected
socket
accept also fills in client’s IP address
Cox & Ng
Networking
68
Echo Server: accept Illustrated
listenfd(3)
Server
Client
clientfd
Connection
request
Client
listenfd(3)
Server
clientfd
listenfd(3)
Client
clientfd
Cox & Ng
1. Server blocks in accept,
waiting for connection
request on listening
descriptor listenfd
Server
connfd(4)
Networking
2. Client makes connection
request by calling and blocking in
connect
3. Server returns connfd from
accept. Client returns from
connect. Connection is now
established between clientfd
and connfd
69
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
Cox & Ng
Networking
70
Echo Server: Identifying the Client
The server can determine the domain name
and IP address of the client
struct hostent *hp;
char *haddrp;
/* pointer to DNS host entry */
/* pointer to dotted decimal string */
hp = Gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr), AF_INET);
haddrp = inet_ntoa(clientaddr.sin_addr);
printf("server connected to %s (%s)\n", hp->h_name, haddrp);
Cox & Ng
Networking
71
Echo Server: echo
The server uses RIO to read and echo text
lines until EOF (end-of-file) is encountered
 EOF notification caused by client calling
close(clientfd)
 IMPORTANT: EOF is a condition, not a particular
data byte
void echo(int connfd) {
size_t n;
char buf[MAXLINE];
rio_t rio;
Rio_readinitb(&rio, connfd);
while((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0) {
printf("server received %d bytes\n", n);
Rio_writen(connfd, buf, n);
}
}
Cox & Ng
Networking
72
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:
 unix> telnet <host> <portnumber>
 Creates a connection with a server running on
<host> and listening on port <portnumber>
Cox & Ng
Networking
73
Testing the Echo Server With telnet
bass> echoserver 5000
server established connection with KITTYHAWK.CMCL (128.2.194.242)
server received 5 bytes: 123
server established connection with KITTYHAWK.CMCL (128.2.194.242)
server received 8 bytes: 456789
kittyhawk> telnet bass 5000
Trying 128.2.222.85...
Connected to BASS.CMCL.CS.CMU.EDU.
Escape character is '^]'.
123
123
Connection closed by foreign host.
kittyhawk> telnet bass 5000
Trying 128.2.222.85...
Connected to BASS.CMCL.CS.CMU.EDU.
Escape character is '^]'.
456789
456789
Connection closed by foreign host.
kittyhawk>
Cox & Ng
Networking
74
Running the Echo Client and Server
bass> echoserver 5000
server established connection with KITTYHAWK.CMCL (128.2.194.242)
server received 4 bytes: 123
server established connection with KITTYHAWK.CMCL (128.2.194.242)
server received 7 bytes: 456789
...
kittyhawk> echoclient bass 5000
Please enter msg: 123
Echo from server: 123
kittyhawk> echoclient bass 5000
Please enter msg: 456789
Echo from server: 456789
kittyhawk>
Cox & Ng
Networking
75
For More Information
W. Richard Stevens, “Unix Network
Programming: Networking APIs: Sockets and
XTI”, Volume 1, Second Edition, Prentice
Hall, 1998.
 THE network programming bible
Complete versions of the echo client and
server are developed in the text
 Available on the course web site
 You should compile and run them for yourselves to
see how they work
 Feel free to borrow any of this code
Cox & Ng
Networking
76
Web History
1945:
 Vannevar Bush, “As we may think”, Atlantic
Monthly, July, 1945
• Describes the idea of a distributed hypertext system
• A “memex” that mimics the “web of trails” in our
minds
1989:
 Tim Berners-Lee (CERN) writes internal proposal to
develop a distributed hypertext system
• Connects “a web of notes with links”
• Intended to help CERN physicists in large projects
share and manage information
1990:
 Tim Berners-Lee writes a graphical browser for
Next machines
Cox & Ng
Networking
77
Web History (cont)
1992
 NCSA server released
 26 WWW servers worldwide
1993
 Marc Andreessen releases first version of NCSA
Mosaic browser
 Mosaic version released for (Windows, Mac, Unix)
 Web (port 80) traffic at 1% of NSFNET backbone
traffic
 Over 200 WWW servers worldwide
1994
 Andreessen and colleagues leave NCSA to form
"Mosaic Communications Corp" (became Netscape,
then part of AOL)
Cox & Ng
Networking
78
Internet Hosts
ISC Domain Survey Host Count
600,000,000
500,000,000
400,000,000
300,000,000
200,000,000
100,000,000
Jan-08
Jan-07
Jan-06
Jan-05
Jan-04
Jan-03
Jan-02
Jan-01
Jan-00
Jan-99
Jan-98
0
Source: www.isc.org
Cox & Ng
Networking
79
Web Servers
Clients and servers
communicate using the
HyperText Transfer
Protocol (HTTP)
 Client and server
HTTP request
establish TCP connection
 Client requests content
 Server responds with
requested content
 Client and server (may)
close connection
Web
client
(browser)
Web
server
HTTP response
(content)
Current version is
HTTP/1.1
 RFC 2616, June, 1999
Cox & Ng
Networking
80
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
HTML document
 text/plain
Unformatted text
 application/postscript Postcript document
 image/gif
Binary image (GIF format)
 image/jpeg
Binary image (JPEG format)
 text/html
Cox & Ng
Networking
81
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
 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 (i.e., search results)
Bottom line: All Web content is associated
with a file that is managed by the server
Cox & Ng
Networking
82
URLs
Each file managed by a server has a unique name called
a URL (Universal Resource Locator)
URLs for static content:
 http://www.rice.edu:80/index.html
 http://www.rice.edu/index.html
 http://www.rice.edu
• Identifies a file called index.html, managed by a Web server
at www.rice.edu that is listening on port 80
URLs for dynamic content:
 http://www.cs.cmu.edu:8000/cgi-bin/adder?15000&213
• Identifies an executable file called adder, managed by a Web
server at www.cs.cmu.edu that is listening on port 8000, that
should be called with two argument strings: 15000 and 213
Cox & Ng
Networking
83
How Clients and Servers Use URLs
Example URL: http://www.aol.com:80/index.html
Clients use prefix (http://www.aol.com:80) to infer:
 What kind of server to contact (http (Web) server)
 Where the server is (www.aol.com)
 What port the server is listening on (80)
Servers use suffix (/index.html) to:
 Determine if request is for static or dynamic content
• No hard and fast rules for this
• 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 servers expand to some default
home page (e.g., index.html)
Cox & Ng
Networking
84
Anatomy of an HTTP Transaction
unix> telnet www.google.com 80
Trying 209.85.164.104...
Connected to www.l.google.com.
Escape character is '^]'.
GET / HTTP/1.1
host: www.google.com
Client: open connection to server
Telnet prints 3 lines to the terminal
Client: request line
Client: required HTTP/1.1 HOST header
Client: empty line terminates headers
HTTP/1.1 200 OK
Server: response line
Cache-Control: private
Server: followed by six response headers
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=<..snip..>
Server: gws
Transfer-Encoding: chunked
Date: Tue, 13 Nov 2007 17:25:04 GMT
Server: empty line (“\r\n”) terminates hdrs
<html>
Server: first HTML line in response body
<..snip..>
Server: HTML content not shown.
</html>
Server: last HTML line in response body
Connection closed by foreign host. Server: closes connection
unix>
Client: closes connection and terminates
Cox & Ng
Networking
85
HTTP Requests
HTTP request is a request line, followed by
zero or more request headers
Request line: <method> <uri> <version>
 <method> is either GET, POST, OPTIONS, HEAD, PUT,
DELETE, or TRACE
 <uri> is typically URL for proxies, URL suffix for
servers
 <version> is HTTP version of request (HTTP/1.0 or
HTTP/1.1)
Cox & Ng
Networking
86
HTTP Requests (cont)
HTTP methods:
 GET: Retrieve static or dynamic content
• Arguments for dynamic content are in URI
• Workhorse method (99% of requests)
 POST: Retrieve dynamic content
• Arguments for dynamic content are in the request
body
 OPTIONS: Get server or file attributes
 HEAD: Like GET but no data in response body
 PUT: Write a file to the server!
 DELETE: Delete a file on the server!
 TRACE: Echo request in response body
• Useful for debugging
Cox & Ng
Networking
87
HTTP Requests (cont)
Request headers: <header name>: <header data>
 Provide additional information to the server
Major differences between HTTP/1.1 and
HTTP/1.0
 HTTP/1.0 uses a new connection for each transaction
 HTTP/1.1 also supports persistent connections
• Multiple transactions over the same connection
• Connection: Keep-Alive
 HTTP/1.1 requires HOST header
• Host: www.yahoo.com
 HTTP/1.1 adds additional support for caching
Cox & Ng
Networking
88
HTTP Responses
HTTP response is a response line followed by zero or
more response headers
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
• 403
• 404
OK
Forbidden
Not found
Request was handled without error
Server lacks permission to access file
Server 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
Cox & Ng
Networking
89
GET Request to Apache Server
From Firefox Browser
GET /~comp221/proxytest.html HTTP/1.1
Host: www.owlnet.rice.edu
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.8)
Gecko/20071022 Ubuntu/7.10 (gutsy) Firefox/2.0.0.8
Accept: text/xml,application/xml,application/xhtml+xml,text/html;
q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Keep-Alive: 300
CRLF (\r\n)
Cox & Ng
Networking
90
GET Response From Apache Server
HTTP/1.1 200 OK
Date: Tue, 13 Nov 2007 18:09:01 GMT
Server: Apache/1.3.26 (Unix) mod_ssl/2.8.9 OpenSSL/0.9.6e
Last-Modified: Tue, 13 Nov 2007 18:08:44 GMT
ETag: “ac330311-df-4739e82c"
Accept-Ranges: bytes
Content-Length: 212
Connection: close
Content-Type: text/html
CRLF
<html>
<head><title>COMP221 Web Proxy Test Page</title></head>
<body><h1>COMP221 Web Proxy Test Page</h1>
This page is a simple text-only HTML file that can be used
to test your web proxy software.
</body></html>
Cox & Ng
Networking
91
Serving Dynamic Content
Client sends request to
server
Server parses request URI
to determine if request is
for static or dynamic
content
GET /cgi-bin/env.pl HTTP/1.1
Client
Server
 In the “old” days, this
was as simple as the
string “/cgi-bin”
starting the URL
 Web servers are far
more flexible and
configurable now
Cox & Ng
Networking
92
Serving Dynamic Content (cont)
The server creates a child
process and runs the
program identified by the
URI in that process
Client
Server
fork/exec
env.pl
Cox & Ng
Networking
93
Serving Dynamic Content (cont)
The child runs and
generates the dynamic
content
Client
The server captures the
content of the child and
forwards it without
modification to the client
Cox & Ng
Networking
Content
Server
Content
env.pl
94
Issues in Serving Dynamic Content
How does the client pass
program arguments to the
server?
Request
How does the server pass
these arguments to the child?
How does the server pass
other info relevant to the
request to the child?
Client
Content Server
Content
How does the server capture
the content produced by the
child?
Create
env.pl
These issues are addressed
by the Common Gateway
Interface (CGI) specification
Cox & Ng
Networking
95
CGI
Because the children are written according to
the CGI spec, they are often called CGI
programs
Because many CGI programs are written in
Perl, they are often called CGI scripts
However, CGI really defines a simple standard
for transferring information between the
client (browser), the server, and the child
process
Cox & Ng
Networking
96
add.com: THE Internet addition portal!
Ever need to add two numbers together and
you just can’t find your calculator?
Try the addition service at “add.com: THE
Internet addition portal!”
 Takes as input the two numbers you want to add
together
 Returns their sum in a tasteful personalized
message
Cox & Ng
Networking
97
The add.com Experience
input URL
host
port
CGI program
args
Output page
Cox & Ng
Networking
98
Serving Dynamic Content With GET
Question: How does the
to the server?
Answer: The arguments
URI
Can be encoded directly
browser or a URL in an
client pass arguments
are appended to the
in a URL typed to a
HTML link
 http://add.com/cgi-bin/adder?1&2
 adder is the CGI program on the server that will do
the addition
 argument list starts with “?”
 arguments separated by “&”
 spaces represented by “+” or “%20”
Can also be generated by an HTML form
<form method=get action="http://add.com/cgi-bin/postadder">
Cox & Ng
Networking
99
Serving Dynamic Content With GET
URL:
 http://add.com/cgi-bin/adder?1&2
Result displayed on browser:
Welcome to add.com: THE Internet addition portal.
The answer is: 1 + 2 = 3
Thanks for visiting! Tell your friends.
Cox & Ng
Networking
100
Serving Dynamic Content With GET
Question: How does the server pass these
arguments to the child?
Answer: In environment variable
QUERY_STRING
 A single string containing everything after the “?”
 For add.com: QUERY_STRING = “1&2”
/* child code that accesses the argument list */
if ((buf = getenv("QUERY_STRING")) == NULL) {
exit(1);
}
/* extract arg1 and arg2 from buf and convert */
...
n1 = atoi(arg1);
n2 = atoi(arg2);
Cox & Ng
Networking
101
Serving Dynamic Content With GET
Question: How does the server pass other info
relevant to the request to the child?
Answer: In a collection of environment
variables defined by the CGI spec
Cox & Ng
Networking
102
Some CGI Environment Variables
General
 SERVER_SOFTWARE
 SERVER_NAME
 GATEWAY_INTERFACE (CGI version)
Request-specific
 SERVER_PORT
 REQUEST_METHOD (GET, POST, etc)
 QUERY_STRING (contains GET arguments)
 REMOTE_HOST (domain name of client)
 REMOTE_ADDR (IP address of client)
 CONTENT_TYPE (for POST, type of data in message
body, e.g., text/html)
 CONTENT_LENGTH (length in bytes)
Cox & Ng
Networking
103
Some CGI Environment Variables
In addition, the value of each header of type
type received from the client is placed in
environment variable HTTP_type
 Examples:
• HTTP_ACCEPT
• HTTP_HOST
• HTTP_USER_AGENT (any “-” is changed to “_”)
Cox & Ng
Networking
104
Serving Dynamic Content With GET
Question: How does the server capture the content
produced by the child?
Answer: The child generates its output on stdout
 Server uses dup2 to redirect stdout to its connected
socket
 Notice that only the child knows the type and size of the
content, so the child (not the server) must generate the
corresponding headers
/* child generates the result string */
sprintf(content, "Welcome to add.com: THE Internet addition portal\
<p>The answer is: %d + %d = %d\
<p>Thanks for visiting!\r\n",
n1, n2, n1+n2);
/* child generates the headers and dynamic content */
printf("Content-length: %d\r\n", strlen(content));
printf("Content-type: text/html\r\n");
printf("\r\n");
printf("%s", content);
Cox & Ng
Networking
105
Serving Dynamic Content With GET
bass> ./tiny 8000
GET /cgi-bin/adder?1&2 HTTP/1.1
Host: bass.cmcl.cs.cmu.edu:8000
<CRLF>
HTTP request received by
Tiny Web server
kittyhawk> telnet bass 8000
Trying 128.2.222.85...
Connected to BASS.CMCL.CS.CMU.EDU.
Escape character is '^]'.
GET /cgi-bin/adder?1&2 HTTP/1.1
Host: bass.cmcl.cs.cmu.edu:8000
HTTP request sent by client
<CRLF>
HTTP/1.1 200 OK
HTTP response generated by
Server: Tiny Web Server
the server
Content-length: 102
HTTP response generated by
Content-type: text/html
the CGI program
<CRLF>
Welcome to add.com: THE Internet addition portal.
<p>The answer is: 1 + 2 = 3
<p>Thanks for visiting!
Connection closed by foreign host.
kittyhawk>
Cox & Ng
Networking
106
Proxies
A proxy is an intermediary between a client
and an origin server
 To the client, the proxy acts like a server
 To the server, the proxy acts like a client
HTTP request
Client
Origin
Server
Proxy
HTTP response
Cox & Ng
HTTP request
HTTP response
Networking
107
Why Proxies?
Can perform useful functions as requests and
responses pass through
 Examples: Caching, logging, anonymization
Client
A
Request foo.html
foo.html
Request foo.html
Client
B
Request foo.html
Proxy
cache
foo.html
Origin
Server
Slower more
expensive
global network
foo.html
Fast inexpensive local network
Cox & Ng
Networking
108
For More Information
Study the Tiny Web server described in your
text
 Tiny is a sequential Web server
 Serves static and dynamic content to real browsers
• text files, HTML files, GIF and JPEG images
 220 lines of commented C code
 Also comes with an implementation of the CGI
script for the add.com addition portal
Cox & Ng
Networking
109
Next Time
Concurrency
Cox & Ng
Networking
110