A Client-Server Transaction. Systemprogrammering 2006 Föreläsning 8 Network Programming. Hardware Org of a Network Host.



Similar documents
Network Programming with Sockets. Anatomy of an Internet Connection

A Client Server Transaction. Introduction to Computer Systems /18 243, fall th Lecture, Nov. 3 rd

Overview of Computer Networks

Network Programming. Chapter The Client-Server Programming Model

Introduction to Socket programming using C

Socket Programming. Kameswari Chebrolu Dept. of Electrical Engineering, IIT Kanpur

Introduction to Socket Programming Part I : TCP Clients, Servers; Host information

INTRODUCTION UNIX NETWORK PROGRAMMING Vol 1, Third Edition by Richard Stevens

Socket Programming in C/C++

TCP/IP - Socket Programming

Tutorial on Socket Programming

Socket Programming. Request. Reply. Figure 1. Client-Server paradigm

Socket Programming. Srinidhi Varadarajan

Porting applications & DNS issues. socket interface extensions for IPv6. Eva M. Castro. ecastro@dit.upm.es. dit. Porting applications & DNS issues UPM

Lab 4: Socket Programming: netcat part

NS3 Lab 1 TCP/IP Network Programming in C

Unix Network Programming

Implementing Network Software

ELEN 602: Computer Communications and Networking. Socket Programming Basics

Writing a C-based Client/Server

DNS Domain Name System

Hostnames. HOSTS.TXT was a bottleneck. Once there was HOSTS.TXT. CSCE515 Computer Network Programming. Hierarchical Organization of DNS

CS640: Computer Networks. Naming /ETC/HOSTS

IT304 Experiment 2 To understand the concept of IPC, Pipes, Signals, Multi-Threading and Multiprocessing in the context of networking.

Elementary Name and Address. Conversions

Writing Client/Server Programs in C Using Sockets (A Tutorial) Part I. Session Greg Granger grgran@sas. sas.com. SAS/C & C++ Support

Concurrent Server Design Alternatives

BSD Sockets Interface Programmer s Guide

CSE 333 SECTION 6. Networking and sockets

UNIX. Sockets. mgr inż. Marcin Borkowski

Packet Sniffing and Spoofing Lab

UNIX Sockets. COS 461 Precept 1

Application Architecture

Elementary Name and Address Conversions

Client / Server Programming with TCP/IP Sockets

Network-Oriented Software Development. Course: CSc4360/CSc6360 Instructor: Dr. Beyah Sessions: M-W, 3:00 4:40pm Lecture 2

Session NM059. TCP/IP Programming on VMS. Geoff Bryant Process Software

Networks. Inter-process Communication. Pipes. Inter-process Communication

Windows Socket Programming & IPv6 Translation Middleware

IP Network Layer. Datagram ID FLAG Fragment Offset. IP Datagrams. IP Addresses. IP Addresses. CSCE 515: Computer Network Programming TCP/IP

15-441: Computer Networks Homework 1

ICT SEcurity BASICS. Course: Software Defined Radio. Angelo Liguori. SP4TE lab.

Network Programming with Sockets. Process Management in UNIX

Internet Protocol Address

416 Distributed Systems. Feb 24, 2016 DNS and CDNs

Networks class CS144 Introduction to Computer Networking Goal: Teach the concepts underlying networks Prerequisites:

Objectives of Lecture. Network Architecture. Protocols. Contents

DESIGN AND IMPLEMENT AND ONLINE EXERCISE FOR TEACHING AND DEVELOPMENT OF A SERVER USING SOCKET PROGRAMMING IN C

First Workshop on Open Source and Internet Technology for Scientific Environment: with case studies from Environmental Monitoring

Internetworking and IP Address

Network Programming TDC 561

RARP: Reverse Address Resolution Protocol

Technical Support Information Belkin internal use only

CS3250 Distributed Systems

TCP/IP Fundamentals. OSI Seven Layer Model & Seminar Outline

Operating Systems Design 16. Networking: Sockets

Introduction To Computer Networking

Applications and Services. DNS (Domain Name System)

The POSIX Socket API

Computer Networks Network architecture

Network Models OSI vs. TCP/IP

Overview. Socket Programming. Using Ports to Identify Services. UNIX Socket API. Knowing What Port Number To Use. Socket: End Point of Communication

Chapter 7: Computer Networks, the Internet, and the World Wide Web. Invitation to Computer Science, C++ Version, Third Edition

Note! The problem set consists of two parts: Part I: The problem specifications pages Part II: The answer pages

VMCI Sockets Programming Guide VMware ESX/ESXi 4.x VMware Workstation 7.x VMware Server 2.0

Understanding TCP/IP. Introduction. What is an Architectural Model? APPENDIX

Internet Working 5 th lecture. Chair of Communication Systems Department of Applied Sciences University of Freiburg 2004

BASIC ANALYSIS OF TCP/IP NETWORKS

Ethernet. Ethernet. Network Devices

Communication Systems Internetworking (Bridges & Co)

UPPER LAYER SWITCHING

IBM i Version 7.2. Programming Socket programming IBM

Unix System Administration

How do I get to

Data Communication Networks and Converged Networks

Communications and Networking

Computer Networks - Xarxes de Computadors

TFTP Usage and Design. Diskless Workstation Booting 1. TFTP Usage and Design (cont.) CSCE 515: Computer Network Programming TFTP + Errors

Domain Name System (1)! gethostbyname (2)! gethostbyaddr (2)!

Java Programming: Sockets in Java

Operating System Concepts. Operating System 資 訊 工 程 學 系 袁 賢 銘 老 師

Internet Concepts. What is a Network?

Network Models and Protocols

Computer Networks/DV2 Lab

Guide to TCP/IP, Third Edition. Chapter 3: Data Link and Network Layer TCP/IP Protocols

Remote login (Telnet):

architecture: what the pieces are and how they fit together names and addresses: what's your name and number?

What is CSG150 about? Fundamentals of Computer Networking. Course Outline. Lecture 1 Outline. Guevara Noubir noubir@ccs.neu.

LESSON Networking Fundamentals. Understand TCP/IP

Project 1: Implement a simple hosts framework using UNIX TCP Sockets to demonstrate the concept of Mobile Agents

Internet Control Protocols Reading: Chapter 3

The exam has 110 possible points, 10 of which are extra credit. There is a Word Bank on Page 8. Pages 7-8 can be removed from the exam.

Programming OpenSSL. The Server Perspective. by Sean Walton. Copyright 2001 Sean Walton

Programmation Systèmes Cours 9 UNIX Domain Sockets

Introduction to TCP/IP

Transcription:

Systemprogrammering 2006 Föreläsning 8 Network Programming Topics -server programming model A -Server Transaction Every network application is 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. Networks Internetworks Global IP Internet IP addresses Domain names Connections 4. handles response process 1. sends request 3. Server sends response Server process 2. Server handles request Resource Socket interface Writing clients and servers Note: clients and servers are processes running on hosts (can be the same or different hosts). F8 2 Systemprogrammering 2007 Hardware Org of a Network Host CPU chip Computer Networks register file ALU system bus memory bus A network is a hierarchical system of boxes and wires organized by geographical proximity LAN (local area network) spans a building or campus. MI I/O bridge main memory Ethernet is most prominent example. WAN (wide-area network) spans country or world. Typically high-speed point-to-point phone lines. Expansion slots USB controller graphics adapter I/O bus disk controller network adapter An internetwork (internet) is an interconnected set of networks. The Gobal IP Internet (uppercase I ) is the most famous example of mouse keyboard monitor disk network an internet (lowercase i ) Let s see how we would build an internet from the ground up. F8 3 Systemprogrammering 2007 F8 4 Systemprogrammering 2007

Lowest Level: Ethernet Segment Ethernet segment consists of a collection of hosts connected by wires (twisted pairs) to a hub. Spans room or floor in a building. Operation ports Each Ethernet adapter has a unique 48-bit Mac 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. Now hubs are usually replaced by switches which send data only to the right port host host host 100 Mb/s hub 100 Mb/s F8 5 Systemprogrammering 2007 Next Level: Bridged Ethernet Segment Spans building or campus. Bridges cleverly learn which hosts are reachable from which ports and then selectively copy frames from port to port. A host host host host host X host hub hub host B bridge 100 Mb/s 100 Mb/s 1 Gb/s 100 Mb/s bridge 100 Mb/s Y F8 6 Systemprogrammering 2007 hub host hub host host host host C Conceptual View of LANs For simplicity, hubs, bridges, and wires are often shown as a collection of hosts attached to a single wire: 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 host host host host LAN 1 router router router WAN WAN LAN 2 LAN 1 and LAN 2 might be completely different, totally incompatible LANs (e.g., Ethernet and ATM) F8 7 Systemprogrammering 2007 F8 8 Systemprogrammering 2007

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. 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. F8 9 Systemprogrammering 2007 F8 10 Systemprogrammering 2007 Transferring Data Over an internet Other Issues (1) (2) data internet packet data PH Host A client protocol software Host B server (8) protocol software (7) data data PH 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? (3) LAN1 frame LAN1 adapter Router LAN2 adapter data PH FH1 LAN1 LAN2 (6) data PH FH2 LAN1 adapter adapter LAN2 frame LAN2 (4) data PH FH1 data PH FH2 (5) What if packets get lost? These (and other) questions are addressed by the area of systems known as computer networking. protocol software F8 11 Systemprogrammering 2007 F8 12 Systemprogrammering 2007

Global IP Internet Most famous example of an internet. Based on the TCP/IP protocol family IP (Internet protocol) (v. 4, v. 6): 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-toprocess. 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. Hardware and Software Org of an Internet Application Sockets interface (system calls) Hardware interface (interrupts) Internet client host TCP/IP Network adapter User code Kernel code Hardware and firmware Global IP Internet Internet server host Server TCP/IP Network adapter F8 13 Systemprogrammering 2007 F8 14 Systemprogrammering 2007 A Programmer s View of the Internet 1. Hosts are mapped to a set of 32-bit IP addresses (v. 4). 128.2.203.179 IP v. 6 has 128-bit addresses, but is, so far, rarely used 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. F8 15 Systemprogrammering 2007 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 { 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. F8 16 Systemprogrammering 2007

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. F8 17 Systemprogrammering 2007 2. Internet Domain Names unnamed root mil edu gov com First-level domain names mit cmu berkeley amazon Second-level domain names cs ece www Third-level domain names 208.216.181.15 cmcl pdl kittyhawk imperial 128.2.194.242 128.2.189.40 F8 18 Systemprogrammering 2007 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; /* official domain name of host */ char **h_aliases; /* null-terminated array of domain names */ int h_addrtype; /* host address type (AF_INET) */ int h_length; /* length of an address, in bytes */ char **h_addr_list; /* 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. F8 19 Systemprogrammering 2007 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-1 mapping between domain name and IP addr: kittyhawk.cmcl.cs.cmu.edu maps to 128.2.194.242 Multiple domain names mapped to the same IP address: eecs.mit.edu and cs.mit.edu both map to 18.62.1.6 Multiple domain names mapped to multiple IP addresses: aol.com and www.aol.com map to multiple IP addrs. Some valid domain names don t map to any IP address: for example: cmcl.cs.cmu.edu F8 20 Systemprogrammering 2007

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)); F8 21 Systemprogrammering 2007 3. Internet Connections s 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 IPaddress: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) F8 22 Systemprogrammering 2007 Internet Connections s Examples of client programs Web browsers, ftp, telnet, ssh host address 128.2.194.242 socket address 128.2.194.242:51213 Note: 51213 is an ephemeral port allocated by the kernel Connection socket pair (128.2.194.242:51213, 208.216.181.15:80) Server socket address 208.216.181.15:80 Server (port 80) Server host address 208.216.181.15 Note: 80 is a well-known port associated with Web servers F8 23 Systemprogrammering 2007 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 know ports Port 7: Echo server Port 23: Telnet server Port 25: Mail server Port 80: Web server F8 24 Systemprogrammering 2007

Using Ports to Identify Services Servers host Service request for 128.2.194.242:80 (i.e., the Web server) Server host 128.2.194.242 Web server (port 80) Kernel Echo server (port 7) 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 7: echo server Port 23: telnet server Service request for 128.2.194.242:7 (i.e., the echo server) Kernel Web server (port 80) Echo server (port 7) Port 25: mail server Port 80: HTTP server A machine that runs a server process is also often referred to as a server. F8 25 Systemprogrammering 2007 F8 26 Systemprogrammering 2007 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) See /etc/services for a Resource: files comprehensive list of the Service: stores and retrieve files services available on a Unix Telnet server (23) machine. Resource: terminal Service: proxies a terminal on the server machine Mail server (25) Resource: email spool file Service: stores mail messages in spool file 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. F8 27 Systemprogrammering 2007 F8 28 Systemprogrammering 2007

Overview of the Sockets Interface Server Sockets socket socket What is a socket? bind open_listenfd To the kernel, a socket is an endpoint of communication. open_clientfd connect Connection request listen accept 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. rio_writen rio_readlineb rio_readlineb rio_writen Await connection request from next client s and servers communicate with each by reading from and writing to socket descriptors. close EOF rio_readlineb close The main distinction between regular file I/O and socket I/O is how the application opens the socket descriptors. F8 29 Systemprogrammering 2007 F8 30 Systemprogrammering 2007 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. struct sockaddr { unsigned short sa_family; /* protocol family */ char sa_data[14]; /* address data. */ ; Internet-specific socket address: Must cast (sockaddr_in *) to (sockaddr *) for connect, bind, and accept. struct sockaddr_in { unsigned short sin_family; /* address family (always AF_INET) */ unsigned short 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) */ ; F8 31 Systemprogrammering 2007 Echo Main Routine #include "csapp.h" /* usage:./echoclient host port */ int main(int argc, char **argv) { 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); F8 32 Systemprogrammering 2007

Echo : open_clientfd int open_clientfd(char *hostname, int port) { int clientfd; struct hostent *hp; struct sockaddr_in serveraddr; if ((clientfd = socket(af_inet, SOCK_STREAM, 0)) < 0) /* 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); This function opens a connection from the client to the server at hostname:port /* Establish a connection with the server */ if (connect(clientfd, (SA *) &serveraddr, sizeof(serveraddr)) < 0) return clientfd; F8 33 Systemprogrammering 2007 Echo : 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) /* check errno for cause of error */ (more) F8 34 Systemprogrammering 2007 Echo : 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); Echo : open_clientfd (connect) Finally the client creates a connection with the server. 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 sockfd. 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 clientfd; F8 35 Systemprogrammering 2007 F8 36 Systemprogrammering 2007

Echo Server: Main Routine Echo Server: open_listenfd 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 a port passed on the command line */ 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); F8 37 Systemprogrammering 2007 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) /* Eliminates "Address already in use" error from bind. */ if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int)) < 0) (more) F8 38 Systemprogrammering 2007 Echo Server: open_listenfd (cont) Echo Server: open_listenfd (socket) /* 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) /* Make it a listening socket ready to accept connection requests */ if (listen(listenfd, LISTENQ) < 0) 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 listenfd; F8 39 Systemprogrammering 2007 F8 40 Systemprogrammering 2007

Echo Server: 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) Handy trick that allows us to rerun the server immediately after we kill it. Otherwise we would have to wait about 15 secs. Eliminates Address already in use error from bind(). Strongly suggest you do this for all your servers to simplify debugging. F8 41 Systemprogrammering 2007 Echo Server: open_listenfd (initialize 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 addr 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. F8 42 Systemprogrammering 2007 Echo Server: 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) Echo Server: 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 listenfd; We re finally ready to enter the main server loop that accepts and processes client connection requests. F8 43 Systemprogrammering 2007 F8 44 Systemprogrammering 2007

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 */ F8 45 Systemprogrammering 2007 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) but with a new (ephemeral) port. 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. F8 46 Systemprogrammering 2007 Echo Server: accept Illustrated Usually a known port listenfd(3) 1. Server blocks in accept, waiting for connection request Server on listening descriptor clientfd listenfd. Connection listenfd(3) request 2. makes connection request Server by calling and blocking in connect. clientfd listenfd(3) 3. Server returns connfd from accept. returns from connect. Server Connection is now established clientfd connfd(4) between clientfd and connfd. New ephemeral port F8 47 Systemprogrammering 2007 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 (more about this in later lectures). F8 48 Systemprogrammering 2007

Echo Server: Identifying the The server can determine the domain name and IP address of the client. struct hostent *hp; /* pointer to DNS host entry */ char *haddrp; /* 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); F8 49 Systemprogrammering 2007 Echo Server: echo The server uses RIO to read and echo text lines until EOF (end-of-file) is encountered. void echo(int connfd) { size_t n; char buf[maxline]; rio_t rio; EOF notification caused by client calling close(clientfd). IMPORTANT: EOF is a condition, not a particular data byte. Rio_readinitb(&rio, connfd); while((n = Rio_readlineb(&rio, buf, MAXLINE))!= 0) { printf("server received %d bytes\n", n); Rio_writen(connfd, buf, n); F8 50 Systemprogrammering 2007 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>. F8 51 Systemprogrammering 2007 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> F8 52 Systemprogrammering 2007

Running the Echo and Server For More Information 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 W. Richard Stevens, Unix Network Programming: Networking APIs: Sockets and XTI, Volume 1, Second Edition, Prentice Hall, 1998. THE network programming bible. 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> Complete versions of the echo client and server are developed in the text. Available from /info/sysprog06/examples You should compile and run them for yourselves to see how they work. Feel free to borrow any of this code. F8 53 Systemprogrammering 2007 F8 54 Systemprogrammering 2007