Sogang University
Network Programming: Part I
CSE4100: System Programming
Youngjae Kim (PhD)
Copyright By PowCoder代写 加微信 powcoder
https://sites.google.com/site/youkim/home
Distributed Computing and Operating Systems Laboratory (DISCOS)
https://discos.sogang.ac.kr
Office: R911, E-mail:
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
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
¡ì Server activated by request from client (vending machine analogy)
Client process
1. Client sends request 3. Server sends response
Server process
4. Client handles
2. Server handles request
Note: clients and servers are processes running on hosts (can be the same or different hosts)
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Hardware Organization of a Network Host CPU chip
register file
system bus
memory bus
graphics adapter
I/O bridge
main memory
Expansion slots
USB controller
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
disk controller
network adapter
mouse keyboard
Sogang University
Computer Networks
¡é A network is a hierarchical system of boxes and wires organized by geographical proximity
¡ì SAN (System Area Network) spans cluster or machine room ¡ì Switched Ethernet, Quadrics QSW, …
¡ì LAN (Local Area Network) spans a building or campus ¡ì Ethernet is most prominent example
¡ì WAN (Wide Area Network) spans country or world ¡ì Typically high-speed point-to-point phone lines
¡é 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¡±)
¡é Let¡¯s see how an internet is built from the ground up Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Lowest Level: Ethernet Segment
host host host
100 Mb/s hub 100 Mb/s
¡é Ethernet segment consists of a collection of hosts connected by wires (twisted pairs) to a hub
¡é Spans room or floor in a building
¡é Operation
¡ì Each Ethernet adapter has a unique 48-bit address (MAC address)
¡ì E.g., 00:16:ea:e3:54:e6
¡ì 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 on their way out. Bridges (switches, routers) became cheap enough to
replace them
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Next Level: Bridged Ethernet Segment
host host
host host
100 Mb/s 1 Gb/s
host host
100 Mb/s hub
¡é Spans building or campus
¡é Bridges cleverly learn which hosts are reachable from which
ports and then selectively copy frames from port to port
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
host host
Sogang University
Conceptual View of LANs
¡é For simplicity, hubs, bridges, and wires are often shown as a collection of hosts attached to a single wire:
host host … host
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Next Level: internets
¡é Multiple incompatible LANs can be physically connected
by specialized computers called routers
¡é The connected networks are called an internet (lower
host host … host LAN1
host host … host LAN 2
router WAN
LAN 1 and LAN 2 might be completely different, totally incompatible
(e.g., Ethernet, Fibre Channel, 802.11*, T1-links, DSL, …)
WAN router
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Logical Structure of an internet
router router
¡é Ad hoc interconnection of networks ¡ì No particular topology
¡ì Vastly different router & link capacities
¡é Send packets from source to destination by hopping through networks
¡ì Router forms bridge from one network to another ¡ì Different packets may take different routes
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
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
¡ì Protocol is a set of rules that governs how hosts and routers should cooperate when they transfer data from network to network.
¡ì Smooths out the differences between the different networks
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
What Does an internet Protocol Do?
¡é 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
¡é 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
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Transferring internet Data Via Encapsulation
(1) data internet packet
protocol software
protocol software
data PH FH1 LAN1 frame
data PH FH1
LAN1 adapter
LAN2 adapter
LAN1 adapter
LAN2 adapter
(4) data PH: Internet packet header
FH: LAN frame header
LAN2 frame
PH FH2 (5)
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
protocol software
Sogang University
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?
¡é These (and other) questions are addressed by the area of systems known as computer networking
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Global IP Internet (upper case) ¡é Most famous example of an 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
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Hardware and Software Organization of an Internet Application
Internet client host
Kernel code
Hardware and firmware
Global IP Internet
Internet server host
Network adapter
Sockets interface (system calls)
Hardware interface (interrupts)
Network adapter
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
A Programmer¡¯s View of the Internet 1. Hosts are mapped to a set of 32-bit IP addresses
¡ì 128.2.203.179
2. The set of IP addresses is mapped to a set of identifiers called Internet domain names
¡ì 128.2.203.179 is mapped to www.cs.cmu.edu
3. A process on one Internet host can communicate with a
process on another Internet host over a connection
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Aside: IPv4 and IPv6
¡é The original Internet Protocol, with its 32-bit addresses, is
known as Internet Protocol Version 4 (IPv4)
¡é 1996: Internet Engineering Task Force (IETF) introduced Internet Protocol Version 6 (IPv6) with 128-bit addresses
¡ì Intended as the successor to IPv4
¡é As of 2015, vast majority of Internet traffic still carried by IPv4
¡ì Only 4% of users access Google services using IPv6.
¡é We will focus on IPv4, but will show you how to write networking code that is protocol-independent.
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
(1) 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 {
uint32_t s_addr; /* network byte order (big-endian) */
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
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
¡é Usegetaddrinfoandgetnameinfofunctions(described
later) to convert between IP addresses and dotted decimal format.
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
(2) Internet Domain Names
ics whaleshark
128.2.210.175
unnamed root
.edu .gov .com
cmu berkeley amazon
First-level domain names Second-level domain names
Third-level domain names
128.2.131.66
176.32.98.166
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
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 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
Sogang University
Properties of DNS Mappings
¡é Can explore properties of DNS mappings using nslookup
¡ì Output edited for brevity
¡é Each host has a locally defined domain name localhost
which always maps to the loopback address 127.0.0.1
¡é Use hostname to determine real domain name of local host:
linux> nslookup localhost Address: 127.0.0.1
linux> hostname whaleshark.ics.cs.cmu.edu
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Properties of DNS Mappings (cont)
¡é Simple case: one-to-one mapping between domain name and IP address:
¡é Multiple domain names mapped to the same IP address:
linux> nslookup whaleshark.ics.cs.cmu.edu Address: 128.2.210.175
linux> nslookup cs.mit.edu Address: 18.62.1.6
linux> nslookup eecs.mit.edu Address: 18.62.1.6
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Properties of DNS Mappings (cont)
¡é Multiple domain names mapped to multiple IP addresses:
linux> nslookup www.twitter.com Address: 199.16.156.6
Address: 199.16.156.70 Address: 199.16.156.102 Address: 199.16.156.230
linux> nslookup twitter.com Address: 199.16.156.102 Address: 199.16.156.230 Address: 199.16.156.6 Address: 199.16.156.70
¡é Some valid domain names don¡¯t map to any IP address: Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
linux> nslookup ics.cs.cmu.edu
*** Can’t find ics.cs.cmu.edu: No answer
Sogang University
(3) Internet Connections
¡é Clients and servers communicate by sending streams of bytes
over 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
¡é A port is a 16-bit integer that identifies a process:
¡ì Ephemeral port: Assigned automatically by client kernel 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)
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Well-known Ports and Service Names
¡é Popular services have permanently assigned well-known
ports and corresponding well-known service names:
¡ì echo server: 7/echo
¡ì ssh servers: 22/ssh
¡ì email server: 25/smtp ¡ì Web servers: 80/http
¡é Mappings between well-known ports and service names is contained in the file /etc/services on each Linux machine.
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Anatomy of a Connection
¡é A connection is uniquely identified by the socket
addresses of its endpoints (socket pair)
¡ì (cliaddr:cliport, servaddr:servport)
Client socket address Server socket address
128.2.194.242:51213 208.216.181.15:80 Connection socket pair
Client host address
128.2.194.242
(128.2.194.242:51213, 208.216.181.15:80)
Server host address
208.216.181.15
80 is a well-known port associated with Web servers
51213 is an ephemeral port
allocated by the kernel
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Server (port 80)
Sogang University
Using Ports to Identify Services
Client host
Service request for 128.2.194.242:80 (i.e., the Web server)
Service request for 128.2.194.242:7 (i.e., the echo server)
Server host 128.2.194.242
Web server (port 80)
Echo server (port 7)
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Web server (port 80)
Echo server (port 7)
Sogang University
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
Sogang University
¡é 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
Client Server
clientfd serverfd
¡é 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
Sogang University
Socket Address Structures
¡é Generic socket address:
¡ì For address arguments to connect, bind, and accept
¡ì Necessary only because C did not have generic (void *) pointers when the sockets interface was designed
¡ì For casting convenience, we adopt the Stevens convention: typedef struct sockaddr SA;
struct sockaddr {
uint16_t sa_family; /* Protocol family */ char sa_data[14]; /* Address data. */
Family Specific
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Socket Address Structures ¡é Internet-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
sin_family
Family Specific
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
2. Start client Client
getaddrinfo socket
1. Start server Server
getaddrinfo socket bind listen
Sockets Interface
open_listenfd
open_clientfd
Connection request
rio_writen rio_readlineb rio_readlineb rio_writen
Client / Server Session
3. Exchange data
Await connection request from next client
4. Disconnect client
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
rio_readlineb
5. Drop client
Sogang University
getaddrinfo
getaddrinfo
bind listen
Sockets Interface
open_listenfd
open_clientfd
Connection request
Client / Server Session
Await connection request from next client
rio_writen rio_readlineb rio_readlineb rio_writen
Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
rio_readlineb close
Sogang University
Host and Service Conversion: getaddrinfo
¡é getaddrinfo is the modern way to convert string representations of hostnames, host addresses, ports, and service names to socket address structures.
¡ì Replaces obsolete gethostbyname and getservbyname funcs.
¡é Advantages:
¡ì Reentrant (can be safely used by threaded programs). ¡ì Allows us to write portable protocol-independent code
¡ì Works with both IPv4 and IPv6 ¡é Disadvantages
¡ì Somewhat complex
¡ì Fortunately, a small number of usage patterns suffice in most Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Host and Service Conversion: getaddrinfo
int getaddrinfo(const char *host, /* Hostname or address */ const char *service, /* Port or service name
const struct addrinfo *hints,/* Input parameters */ struct addrinfo **result); /* Output linked list */
void freeaddrinfo(struct addrinfo *result); /* Free linked list */
const char *gai_strerror(int errcode); /* Return error msg */
¡é Givenhostandservice,getaddrinfo returnsresult that points to a linked list of addrinfo structs, each of which points to a corresponding socket address struct, and which contains arguments for the sockets interface functions.
¡é Helper functions:
¡ì freeadderinfo frees the entire linked list.
¡ì gai_strerror converts error code to an error message. Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
Linked List Returned by getaddrinfo addrinfo structs
ai_canonname
Socket address structs
¡é Clients: walk this list, trying each socket address in turn, until the calls to socket and connect succeed.
¡é Servers: walk the list until calls to socket and bind succeed. Bryant and O¡¯Hallaron, Computer Systems: A Programmer¡¯s Perspective, Third Edition
Sogang University
addrinfo Struct
struct addrinfo { int
ai_flags; ai_family; ai_socktype; ai_protocol;
/* Hints argument flags */
/* First arg to socket function */ /* Second arg to socket function */ /* Third arg to socket function */ /* Canonical host name */
/* Size of ai_addr stru
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com