Introduction to Unix Network Programming Reference Stevens Unix

  • Slides: 63
Download presentation
Introduction to Unix Network Programming Reference: Stevens Unix Network Programming 8/30/06 UIUC - CS/ECE

Introduction to Unix Network Programming Reference: Stevens Unix Network Programming 8/30/06 UIUC - CS/ECE 438, Fall 2006

How do we Communicate? n Send a mail from Alice to Bob Alice in

How do we Communicate? n Send a mail from Alice to Bob Alice in Champaign, Bob in Hollywood ¡ n Bob Example: US Postal Service ¡ Alice Hollywood, California Champaign, Illinois 8/30/06 UIUC - CS/ECE 438, Fall 2006 2

What does Alice do? Alice 200 Cornfield Rd. Champaign, IL 61820 Bob 100 Santa

What does Alice do? Alice 200 Cornfield Rd. Champaign, IL 61820 Bob 100 Santa Monica Blvd. Hollywood, CA 90028 n n 8/30/06 Bob’s address (to a mailbox) Bob’s name – in case people share mailbox Postage – have to pay! Alice’s own name and address – in case Bob wants to return a message UIUC - CS/ECE 438, Fall 2006 3

What does Bob do? Alice 200 Cornfield Rd. Champaign, IL 61820 Bob 100 Santa

What does Bob do? Alice 200 Cornfield Rd. Champaign, IL 61820 Bob 100 Santa Monica Blvd. Hollywood, CA 90028 n n 8/30/06 Install a mailbox Receive the mail Get rid of envelope Read the message UIUC - CS/ECE 438, Fall 2006 4

What about sending a TCP/IP packet? n n Very similar to Alice-mailing-to-Bob Different terminologies

What about sending a TCP/IP packet? n n Very similar to Alice-mailing-to-Bob Different terminologies – very confusing ¡ n Different technologies ¡ 8/30/06 We have to remember Suppose to be better (faster, more reliable, cheaper, …) UIUC - CS/ECE 438, Fall 2006 5

Two simplest networking programs n Alice ¡ ¡ ¡ n the sending process Alice’s

Two simplest networking programs n Alice ¡ ¡ ¡ n the sending process Alice’s address: 128. 174. 246. 177 (IP addr) Alice’s name: 12345 (port #) int main () { int sockfd; struct sockaddr_in bob_addr, alice_addr; bzero(&bob_addr, sizeof(bob_addr)); bob_addr. sin_family = AF_INET; bob_addr. sin_addr. s_addr = 0 x. D 834 A 784; bob_addr. sin_port = 23456; Bob ¡ ¡ ¡ the receiving process Bob’s address: 216. 52. 167. 132 (IP addr) Bob’s name: 23456 (port #) int main () { int sockfd, n; struct sockaddr_in bob_addr, alice_addr; char mesg[100]; bzero(&bob_addr, sizeof(bob_addr)); bob_addr. sin_family = AF_INET; bob_addr. sin_addr. s_addr = 0 x. D 834 A 784; bob_addr. sin_port = 23456; // do the same for alice_addr … sockfd = socket(AF_INET, SOCK_DGRAM, 0); sendto(sockfd, “hi”, strlen(“hi”), 0, &bob_addr, sizeof(bob_addr)); } 8/30/06 sockfd = socket(AF_INET, SOCK_DGRAM, 0); bind(sockfd, &bob_addr, sizeof(bob_addr)); n= recvfrom(sockfd, mesg, 100, 0, &alice_addr, sizeof(alice_addr)); } 2006 UIUC - CS/ECE 438, Fall 6

What are the problems? n Message may be lost ¡ ¡ n n 8/30/06

What are the problems? n Message may be lost ¡ ¡ n n 8/30/06 Network is congested Receiver is congested Message may be duplicated, corrupted Multiple messages: re-ordered Concurrent connections … UIUC - CS/ECE 438, Fall 2006 7

Direction and Principles Programming Transport Network learn to use Internet for communication (with focus

Direction and Principles Programming Transport Network learn to use Internet for communication (with focus on implementation of networking concepts) Data Link Physical learn to build network from ground up Principles and Concepts 8/30/06 UIUC - CS/ECE 438, Fall 2006 8

Sockets n n process sends/receives messages to/from its socket analogous to mailbox ¡ sending

Sockets n n process sends/receives messages to/from its socket analogous to mailbox ¡ sending process relies on transport infrastructure which brings message to socket at receiving process 8/30/06 host or server process controlled by app developer process socket TCP with buffers, variables UIUC - CS/ECE 438, Fall 2006 Internet 9

Network Programming with Sockets n Reading: ¡ n Stevens 2 nd ed. , Ch.

Network Programming with Sockets n Reading: ¡ n Stevens 2 nd ed. , Ch. 1 -6 or 1 st ed. , Ch. 1 -3, 6 Sockets API: ¡ A transport layer service interface n n 8/30/06 Introduced in 1981 by BSD 4. 1 Implemented as library and/or system calls Similar interfaces to TCP and UDP Can also serve as interface to IP (for super-user); known as “raw sockets” UIUC - CS/ECE 438, Fall 2006 10

Outline n n n 8/30/06 Client-Sever Model TCP/UDP Overview Addresses and Data Sockets API

Outline n n n 8/30/06 Client-Sever Model TCP/UDP Overview Addresses and Data Sockets API Example UIUC - CS/ECE 438, Fall 2006 11

Client-Server Model n Asymmetric Communication ¡ Client ¡ n Server/Daemon ¡ Client ¡ Server

Client-Server Model n Asymmetric Communication ¡ Client ¡ n Server/Daemon ¡ Client ¡ Server ¡ Client n Client sends requests Server sends replies Well-known name (e. g. , IP address + port) Waits for contact Processes requests, sends replies Client ¡ ¡ Initiates contact Waits for response Client 8/30/06 UIUC - CS/ECE 438, Fall 2006 12

Socket Communication Client process 3 -way handshaking Client socket 8/30/06 Server process Listening socket

Socket Communication Client process 3 -way handshaking Client socket 8/30/06 Server process Listening socket Connection socket UIUC - CS/ECE 438, Fall 2006 13

Client-Server Communication Model n Service Model ¡ Concurrent: n ¡ Sequential: n ¡ Server

Client-Server Communication Model n Service Model ¡ Concurrent: n ¡ Sequential: n ¡ Server maintains multiple connections, but processes responses sequentially Client and server categories are not disjoint ¡ ¡ 8/30/06 Server processes only one client’s requests at a time Hybrid: n n Server processes multiple clients’ requests simultaneously A server can be a client of another server A server can be a client of its own client UIUC - CS/ECE 438, Fall 2006 14

TCP Connections n Transmission Control Protocol (TCP) Service ¡ ¡ OSI Transport Layer Service

TCP Connections n Transmission Control Protocol (TCP) Service ¡ ¡ OSI Transport Layer Service Model n n n Reliable byte stream (interpreted by application) 16 -bit port space allows multiple connections on a single host Connection-oriented ¡ ¡ 8/30/06 Set up connection before communicating Tear down connection when done UIUC - CS/ECE 438, Fall 2006 15

TCP Service n Reliable Data Transfer ¡ ¡ n Sequenced Data Transfer ¡ ¡

TCP Service n Reliable Data Transfer ¡ ¡ n Sequenced Data Transfer ¡ ¡ n Guarantees in-order delivery of data If A sends M 1 followed by M 2 to B, B never receives M 2 before M 1 Regulated Data Flow ¡ ¡ ¡ n Guarantees delivery of all data Exactly once if no catastrophic failures Monitors network and adjusts transmission appropriately Prevents senders from wasting bandwidth Reduces global congestion problems Data Transmission ¡ 8/30/06 Full-Duplex byte stream UIUC - CS/ECE 438, Fall 2006 16

UDP Services n User Datagram Protocol Service ¡ ¡ ¡ 8/30/06 OSI Transport Layer

UDP Services n User Datagram Protocol Service ¡ ¡ ¡ 8/30/06 OSI Transport Layer Provides a thin layer over IP 16 -bit port space (distinct from TCP ports) allows multiple recipients on a single host UIUC - CS/ECE 438, Fall 2006 17

UDP Services n Unit of Transfer ¡ n Unreliable ¡ ¡ n No guaranteed

UDP Services n Unit of Transfer ¡ n Unreliable ¡ ¡ n No guaranteed delivery Drops packets silently Unordered ¡ n Datagram (variable length packet) No guarantee of maintained order of delivery Unlimited Transmission ¡ 8/30/06 No flow control UIUC - CS/ECE 438, Fall 2006 18

Addresses and Data n Internet domain names ¡ ¡ ¡ n IP addresses ¡

Addresses and Data n Internet domain names ¡ ¡ ¡ n IP addresses ¡ ¡ 8/30/06 Human readable Variable length Ex: sal. cs. uiuc. edu Easily handled by routers/computers Fixed length Somewhat geographical Ex: 128. 174. 252. 217 UIUC - CS/ECE 438, Fall 2006 19

Byte Ordering n Big Endian vs. Little Endian ¡ Little Endian (Intel, DEC): n

Byte Ordering n Big Endian vs. Little Endian ¡ Little Endian (Intel, DEC): n ¡ Big Endian (Sun, SGI, HP): n ¡ Most significant byte of word is stored in the lowest memory address Network Byte Order = Big Endian n 8/30/06 Least significant byte of word is stored in the lowest memory address Allows both sides to communicate Must be used for some data (i. e. IP Addresses) Good form for all binary data UIUC - CS/ECE 438, Fall 2006 20

Byte Ordering Functions 16 - and 32 -bit conversion functions (for platform independence) Examples:

Byte Ordering Functions 16 - and 32 -bit conversion functions (for platform independence) Examples: n n int m, n; short int s, t; m s n t = = 8/30/06 ntohl ntohs htonl htons (n) (t) (m) (s) net-to-host-to-net long (32 -bit) translation short (16 -bit) translation UIUC - CS/ECE 438, Fall 2006 21

Socket Address Structure n IP address: struct in_addr { in_addr_t s_addr; }; n TCP

Socket Address Structure n IP address: struct in_addr { in_addr_t s_addr; }; n TCP or UDP address: struct sockaddr_in { short sin_family; ushort sin_port; struct in_addr; }; n 8/30/06 /* 32 -bit IP address */ /* e. g. , AF_INET */ /* TCP/UDP port */ /* IP address */ all but sin_family in network byte order UIUC - CS/ECE 438, Fall 2006 22

Address Access/Conversion Functions n All binary values are network byte ordered struct hostent* gethostbyname

Address Access/Conversion Functions n All binary values are network byte ordered struct hostent* gethostbyname (const char* hostname); ¡ Translate English host name to IP address (uses DNS) struct hostent* gethostbyaddr (const char* addr, size_t len, int family); ¡ Translate IP address to English host name (not secure) char* inet_ntoa (struct in_addr inaddr); ¡ 8/30/06 Translate IP address to ASCII dotted-decimal notation (e. g. , “ 128. 32. 36. 37”) UIUC - CS/ECE 438, Fall 2006 23

Structure: hostent n The hostent data structure (from /usr/include/netdb. h) ¡ ¡ ¡ canonical

Structure: hostent n The hostent data structure (from /usr/include/netdb. h) ¡ ¡ ¡ canonical domain name and aliases list of addresses associated with machine also address type and length information struct hostent { char* h_name; /* official name of host */ char** h_aliases; /* NULL-terminated alias list */ int h_addrtype /* address type (AF_INET) */ int h_length; /* length of addresses (4 B) */ char** h_addr_list; /* NULL-terminated address list */ #define h_addr_list[0]; /* backward-compatibility */ }; 8/30/06 UIUC - CS/ECE 438, Fall 2006 24

Address Access/Conversion Functions in_addr_t inet_addr (const char* strptr); ¡ Translate dotted-decimal notation to IP

Address Access/Conversion Functions in_addr_t inet_addr (const char* strptr); ¡ Translate dotted-decimal notation to IP address; returns -1 on failure, thus cannot handle broadcast value “ 255” int inet_aton (const char *strptr, struct in_addr *inaddr); ¡ Translate dotted-decimal notation to IP address; returns 1 on success, 0 on failure int gethostname (char* name, size_t namelen); ¡ 8/30/06 Read host’s name (use with gethostbyname to find local IP) UIUC - CS/ECE 438, Fall 2006 25

Sockets API n n n 8/30/06 Basic Unix Concepts Creation and Setup Establishing a

Sockets API n n n 8/30/06 Basic Unix Concepts Creation and Setup Establishing a Connection (TCP) Sending and Receiving Data Tearing Down a Connection (TCP) Advanced Sockets UIUC - CS/ECE 438, Fall 2006 26

UDP Connection Example client server socket bind sendto recvfrom close 8/30/06 UIUC - CS/ECE

UDP Connection Example client server socket bind sendto recvfrom close 8/30/06 UIUC - CS/ECE 438, Fall 2006 27

Functions: sendto int sendto (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr*

Functions: sendto int sendto (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* destaddr, int addrlen); n Send a datagram to another UDP socket. ¡ ¡ ¡ ¡ Returns number of bytes written or -1. Also sets errno on failure. sockfd: socket file descriptor (returned from socket) buf: data buffer nbytes: number of bytes to try to read flags: see man page for details; typically use 0 destaddr: IP address and port number of destination socket addrlen: length of address structure n 8/30/06 = sizeof (struct sockaddr_in) UIUC - CS/ECE 438, Fall 2006 28

Functions: recvfrom int recvfrom (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr*

Functions: recvfrom int recvfrom (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* srcaddr, int* addrlen); n Read a datagram from a UDP socket. ¡ ¡ ¡ ¡ 8/30/06 Returns number of bytes read (0 is valid) or -1. Also sets errno on failure. sockfd: socket file descriptor (returned from socket) buf: data buffer nbytes: number of bytes to try to read flags: see man page for details; typically use 0 srcaddr: IP address and port number of sending socket (returned from call) addrlen: length of address structure = pointer to int set to sizeof (struct sockaddr_in) UIUC - CS/ECE 438, Fall 2006 29

Socket Functions TCP Server socket() TCP Client Well-known port bind() listen() accept() socket() blocks

Socket Functions TCP Server socket() TCP Client Well-known port bind() listen() accept() socket() blocks until connection from client connect() TCP three-way handshaking write() data (request) read() process request 8/30/06 UIUC - CS/ECE 438, Fall 2006 30

Socket Functions socket() TCP Client blocks until connection from client connect() TCP Server TCP

Socket Functions socket() TCP Client blocks until connection from client connect() TCP Server TCP three-way handshaking write() data (request) read() process request write() data (reply) read() close() 8/30/06 close() UIUC - CS/ECE 438, Fall 2006 31

TCP Connection Example client server socket bind socket listen accept connect write read close

TCP Connection Example client server socket bind socket listen accept connect write read close 8/30/06 UIUC - CS/ECE 438, Fall 2006 32

Socket Creation and Setup n n n Include file <sys/socket. h> Create a socket

Socket Creation and Setup n n n Include file <sys/socket. h> Create a socket ¡ int socket (int family, int type, int protocol); ¡ Returns file descriptor or -1. Bind a socket to a local IP address and port number ¡ n Put socket into passive state (wait for connections rather than initiate a connection). ¡ n int bind (int sockfd, struct sockaddr* myaddr, int addrlen); int listen (int sockfd, int backlog); Accept connections ¡ ¡ 8/30/06 int accept (int sockfd, struct sockaddr* cliaddr, int* addrlen); Returns file descriptor or -1. UIUC - CS/ECE 438, Fall 2006 33

Functions: socket int socket (int family, int type, int protocol); n Create a socket.

Functions: socket int socket (int family, int type, int protocol); n Create a socket. ¡ ¡ Returns file descriptor or -1. Also sets errno on failure. family: address family (namespace) n n ¡ type: style of communication n n ¡ SOCK_STREAM for TCP (with AF_INET) SOCK_DGRAM for UDP (with AF_INET) protocol: protocol within family n 8/30/06 AF_INET for IPv 4 other possibilities: AF_INET 6 (IPv 6), AF_UNIX or AF_LOCAL (Unix socket), AF_ROUTE (routing) typically 0 UIUC - CS/ECE 438, Fall 2006 34

Function: bind int bind (int sockfd, struct sockaddr* myaddr, int addrlen); n Bind a

Function: bind int bind (int sockfd, struct sockaddr* myaddr, int addrlen); n Bind a socket to a local IP address and port number. ¡ ¡ ¡ Returns 0 on success, -1 and sets errno on failure. sockfd: socket file descriptor (returned from socket) myaddr: includes IP address and port number n n ¡ addrlen: length of address structure n 8/30/06 IP address: set by kernel if value passed is INADDR_ANY, else set by caller port number: set by kernel if value passed is 0, else set by caller = sizeof (struct sockaddr_in) UIUC - CS/ECE 438, Fall 2006 35

TCP and UDP Ports n Allocated and assigned by the Internet Assigned Numbers Authority

TCP and UDP Ports n Allocated and assigned by the Internet Assigned Numbers Authority ¡ see RFC 1700 or ftp: //ftp. isi. edu/in-notes/iana/assignments/port-numbers 1 -512 8/30/06 n standard services (see /etc/services) n super-user only registered and controlled, also used for identity verification n super-user only 513 -1023 n 1024 -49151 n registered services/ephemeral ports 49152 -65535 n private/ephemeral ports UIUC - CS/ECE 438, Fall 2006 36

Functions: listen int listen (int sockfd, int backlog); n Put socket into passive state

Functions: listen int listen (int sockfd, int backlog); n Put socket into passive state (wait for connections rather than initiate a connection). ¡ ¡ ¡ 8/30/06 Returns 0 on success, -1 and sets errno on failure. sockfd: socket file descriptor (returned from socket) backlog: bound on length of unaccepted connection queue (connection backlog); kernel will cap, thus better to set high UIUC - CS/ECE 438, Fall 2006 37

Functions: accept int accept (int sockfd, struct sockaddr* cliaddr, int* addrlen); n Accept a

Functions: accept int accept (int sockfd, struct sockaddr* cliaddr, int* addrlen); n Accept a new connection. ¡ ¡ n addrlen is a value-result argument: ¡ 8/30/06 Returns file descriptor or -1. Also sets errno on failure. sockfd: socket file descriptor (returned from socket) cliaddr: IP address and port number of client (returned from call) addrlen: length of address structure = pointer to int set to sizeof (struct sockaddr_in) the caller passes the size of the address structure, the kernel returns the size of the client’s address (the number of bytes written) UIUC - CS/ECE 438, Fall 2006 38

server #include <stdio. h> #include <stdlib. h> #include <errno. h> #include <string. h> #include

server #include <stdio. h> #include <stdlib. h> #include <errno. h> #include <string. h> #include <sys/types. h> #include <netinet/in. h> #include <sys/socket. h> #include <sys/wait. h> #define PORT 3490 /* well-known port */ #define BACKLOG 10 /* how many pending connections queue will hold */ 8/30/06 UIUC - CS/ECE 438, Fall 2006 39

server main() { int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd

server main() { int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */ struct sockaddr_in my_addr; /* my address */ struct sockaddr_in their_addr; /* connector addr */ int sin_size; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0))==1){ perror("socket"); exit(1); } 8/30/06 UIUC - CS/ECE 438, Fall 2006 40

server bzero(&my_addr, sizeof(struct sockaddr)); /* zero the struct */ my_addr. sin_family = AF_INET; /*

server bzero(&my_addr, sizeof(struct sockaddr)); /* zero the struct */ my_addr. sin_family = AF_INET; /* host byte order */ my_addr. sin_port = htons(MYPORT); /* short, network byte order */ my_addr. sin_addr. s_addr = htonl(INADDR_ANY); if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } 8/30/06 UIUC - CS/ECE 438, Fall 2006 41

server if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) { /* main

server if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) { /* main accept() loop */ sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr*) &their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %sn", inet_ntoa(their_addr. sin_addr)); 8/30/06 UIUC - CS/ECE 438, Fall 2006 42

Establishing a Connection n Include file <sys/socket. h> int connect (int sockfd, struct sockaddr*

Establishing a Connection n Include file <sys/socket. h> int connect (int sockfd, struct sockaddr* servaddr, int addrlen); ¡ Connect to another socket. 8/30/06 UIUC - CS/ECE 438, Fall 2006 43

Functions: connect int connect (int sockfd, struct sockaddr* servaddr, int addrlen); n Connect to

Functions: connect int connect (int sockfd, struct sockaddr* servaddr, int addrlen); n Connect to another socket. ¡ ¡ Returns 0 on success, -1 and sets errno on failure. sockfd: socket file descriptor (returned from socket) servaddr: IP address and port number of server addrlen: length of address structure n 8/30/06 = sizeof (struct sockaddr_in) UIUC - CS/ECE 438, Fall 2006 44

client if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror (“socket”); exit

client if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror (“socket”); exit (1); } their_addr. sin_family = AF_INET; /* interp’d by host */ their_addr. sin_port = htons (PORT); their_addr. sin_addr = *((struct in_addr*)he->h_addr); bzero (&(their_addr. sin_zero), 8); /* zero rest of struct */ if (connect (sockfd, (struct sockaddr*)&their_addr, sizeof (struct sockaddr)) == -1) { perror (“connect”); exit (1); } 8/30/06 UIUC - CS/ECE 438, Fall 2006 45

Sending and Receiving Data int write (int sockfd, char* buf, size_t nbytes); ¡ Write

Sending and Receiving Data int write (int sockfd, char* buf, size_t nbytes); ¡ Write data to a stream (TCP) or “connected” datagram (UDP) socket. n Returns number of bytes written or -1. int read (int sockfd, char* buf, size_t nbytes); ¡ Read data from a stream (TCP) or “connected” datagram (UDP) socket. n 8/30/06 Returns number of bytes read or -1. UIUC - CS/ECE 438, Fall 2006 46

Sending and Receiving Data int sendto (int sockfd, char* buf, size_t nbytes, int flags,

Sending and Receiving Data int sendto (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* destaddr, int addrlen); ¡ Send a datagram to another UDP socket. n Returns number of bytes written or -1. int recvfrom (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* srcaddr, int* addrlen); ¡ Read a datagram from a UDP socket. n 8/30/06 Returns number of bytes read or -1. UIUC - CS/ECE 438, Fall 2006 47

Functions: write int write (int sockfd, char* buf, size_t nbytes); n Write data to

Functions: write int write (int sockfd, char* buf, size_t nbytes); n Write data to a stream (TCP) or “connected” datagram (UDP) socket. ¡ ¡ n Returns number of bytes written or -1. Also sets errno on failure. sockfd: socket file descriptor (returned from socket) buf: data buffer nbytes: number of bytes to try to write Some reasons for failure or partial writes: n n 8/30/06 process received interrupt or signal kernel resources unavailable (e. g. , buffers) UIUC - CS/ECE 438, Fall 2006 48

Functions: read int read (int sockfd, char* buf, size_t nbytes); n Read data from

Functions: read int read (int sockfd, char* buf, size_t nbytes); n Read data from a stream (TCP) or “connected” datagram (UDP) socket. ¡ ¡ ¡ 8/30/06 Returns number of bytes read or -1. Also sets errno on failure. Returns 0 if socket closed. sockfd: socket file descriptor (returned from socket) buf: data buffer nbytes: number of bytes to try to read UIUC - CS/ECE 438, Fall 2006 49

Tearing Down a Connection int close (int sockfd); ¡ Close a socket. n Returns

Tearing Down a Connection int close (int sockfd); ¡ Close a socket. n Returns 0 on success, -1 and sets errno on failure. int shutdown (int sockfd, int howto); ¡ Force termination of communication across a socket in one or both directions. n 8/30/06 Returns 0 on success, -1 and sets errno on failure. UIUC - CS/ECE 438, Fall 2006 50

Functions: close int close (int sockfd); n Close a socket. ¡ ¡ n Closes

Functions: close int close (int sockfd); n Close a socket. ¡ ¡ n Closes communication on socket in both directions. ¡ n 8/30/06 Returns 0 on success, -1 and sets errno on failure. sockfd: socket file descriptor (returned from socket) All data sent before close are delivered to other side (although this aspect can be overridden). After close, sockfd is not valid for reading or writing. UIUC - CS/ECE 438, Fall 2006 51

Functions: shutdown int shutdown (int sockfd, int howto); n Force termination of communication across

Functions: shutdown int shutdown (int sockfd, int howto); n Force termination of communication across a socket in one or both directions. ¡ ¡ ¡ Returns 0 on success, -1 and sets errno on failure. sockfd: socket file descriptor (returned from socket) howto: n n 8/30/06 SHUT_RD to stop reading SHUT_WR to stop writing SHUT_RDWR to stop both shutdown overrides the usual rules regarding duplicated sockets, in which TCP teardown does not occur until all copies have closed the socket. UIUC - CS/ECE 438, Fall 2006 52

Advanced Sockets n Managing Multiple Connections ¡ ¡ ¡ n Detecting Data Arrival ¡

Advanced Sockets n Managing Multiple Connections ¡ ¡ ¡ n Detecting Data Arrival ¡ n n 8/30/06 fork/exec: multiple server processes pthread_create: multi-threaded server process (no calls): event-based server process select and poll functions Synchronous vs. Asynchronous Connections Other Socket Options UIUC - CS/ECE 438, Fall 2006 53

Examples n Taken from Beej’s Guide to Network Programming: http: //beej. us/guide/bgnet/ ¡ ¡

Examples n Taken from Beej’s Guide to Network Programming: http: //beej. us/guide/bgnet/ ¡ ¡ Client-Server example using TCP For each client n n 8/30/06 server forks new process to handle connection sends “Hello, world” UIUC - CS/ECE 438, Fall 2006 54

server #include <stdio. h> #include <stdlib. h> #include <errno. h> #include <string. h> #include

server #include <stdio. h> #include <stdlib. h> #include <errno. h> #include <string. h> #include <sys/types. h> #include <netinet/in. h> #include <sys/socket. h> #include <sys/wait. h> #define PORT 3490 /* well-known port */ #define BACKLOG 10 /* how many pending connections queue will hold */ 8/30/06 UIUC - CS/ECE 438, Fall 2006 55

server main() { int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd

server main() { int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */ struct sockaddr_in my_addr; /* my address */ struct sockaddr_in their_addr; /* connector addr */ int sin_size; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0))==1){ perror("socket"); exit(1); } 8/30/06 UIUC - CS/ECE 438, Fall 2006 56

server my_addr. sin_family = AF_INET; /* host byte order */ my_addr. sin_port = htons(MYPORT);

server my_addr. sin_family = AF_INET; /* host byte order */ my_addr. sin_port = htons(MYPORT); /* short, network byte order */ my_addr. sin_addr. s_addr = htonl(INADDR_ANY); /* automatically fill with my IP (w/o Beej’s bug) */ bzero(&(my_addr. sin_zero), 8); /* zero the struct */ if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); 8/30/06 } UIUC - CS/ECE 438, Fall 2006 57

server if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) { /* main

server if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) { /* main accept() loop */ sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr*) &their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %sn", inet_ntoa(their_addr. sin_addr)); 8/30/06 UIUC - CS/ECE 438, Fall 2006 58

server if (!fork()) { /* this is the child process */ if (send(new_fd, "Hello,

server if (!fork()) { /* this is the child process */ if (send(new_fd, "Hello, world!n", 14, 0) == -1) perror("send"); close(new_fd); exit(0); } close(new_fd); /* parent doesn't need this */ /* clean up all child processes */ while(waitpid(-1, NULL, WNOHANG) > 0); } } 8/30/06 UIUC - CS/ECE 438, Fall 2006 59

client #include <stdlib. h> #include <errno. h> #include <string. h> #include <netdb. h> #include

client #include <stdlib. h> #include <errno. h> #include <string. h> #include <netdb. h> #include <sys/types. h> #include <netinet/in. h> #include <sys/socket. h> #define PORT 3490 /* well-known port */ #define MAXDATASIZE 100 /* max number of bytes we can get at once */ 8/30/06 UIUC - CS/ECE 438, Fall 2006 60

client int main (int argc, char* argv[]){ int sockfd, numbytes; char buf[MAXDATASIZE + 1];

client int main (int argc, char* argv[]){ int sockfd, numbytes; char buf[MAXDATASIZE + 1]; struct hostent* he; struct sockaddr_in their_addr; /* connector’s address information */ if (argc != 2) { fprintf (stderr, “usage: client hostnamen”); exit (1); } if ((he = gethostbyname (argv[1])) == NULL) { /* get the host info */ perror (“gethostbyname”); exit (1); } 8/30/06 UIUC - CS/ECE 438, Fall 2006 61

client if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror (“socket”); exit

client if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror (“socket”); exit (1); } their_addr. sin_family = AF_INET; /* interp’d by host */ their_addr. sin_port = htons (PORT); their_addr. sin_addr = *((struct in_addr*)he->h_addr); bzero (&(their_addr. sin_zero), 8); /* zero rest of struct */ if (connect (sockfd, (struct sockaddr*)&their_addr, sizeof (struct sockaddr)) == -1) { perror (“connect”); exit (1); } 8/30/06 UIUC - CS/ECE 438, Fall 2006 62

client if ((numbytes = recv (sockfd, buf, MAXDATASIZE, 0)) == -1) { perror (“recv”);

client if ((numbytes = recv (sockfd, buf, MAXDATASIZE, 0)) == -1) { perror (“recv”); exit (1); } buf[numbytes] = ‘’; printf (“Received: %s”, buf); close (sockfd); return 0; } 8/30/06 UIUC - CS/ECE 438, Fall 2006 63