network application programming introduction: issues sockets: programming and implementation other...

70
Network Application Network Application Programming Programming Introduction: Introduction: issues issues Sockets: Sockets: programming and implementation programming and implementation Other API’s: Other API’s: winsock winsock java java transport layer interface (TLI) transport layer interface (TLI) Novell netware API Novell netware API Reading: Reading: Tannenbaum, page 486-487 Tannenbaum, page 486-487 ftp://gaia.cs.umass.edu/cs653/sock.ps ftp://gaia.cs.umass.edu/cs653/sock.ps

Upload: florence-price

Post on 27-Dec-2015

230 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Network Application ProgrammingNetwork Application Programming

Introduction:Introduction: issues issues

Sockets:Sockets: programming and implementation programming and implementation

Other API’s:Other API’s: winsockwinsock javajava transport layer interface (TLI)transport layer interface (TLI) Novell netware APINovell netware APIReading:Reading: Tannenbaum, page 486-487 Tannenbaum, page 486-487

ftp://gaia.cs.umass.edu/cs653/sock.psftp://gaia.cs.umass.edu/cs653/sock.ps

Page 2: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The Application Programming The Application Programming Interface: APIInterface: API

API:API: the programming model, application callable the programming model, application callable services, interfaces, and abstractions provided by services, interfaces, and abstractions provided by the network (i.e., lower layers) to the application.the network (i.e., lower layers) to the application.

does an API provide for:does an API provide for: naming and service location:naming and service location: must application know must application know

precise location (e.g., host address and port) of service? precise location (e.g., host address and port) of service? Can services be requested by name? Can servers Can services be requested by name? Can servers registers services? registers services?

connection management.connection management. must applications do low-level must applications do low-level handshaking required to setup/teardown connection? handshaking required to setup/teardown connection?

Page 3: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The API (continued)The API (continued)Does an API provide for:Does an API provide for: message transfermessage transfer

application-selectable data transfer services: best-effortapplication-selectable data transfer services: best-effortversus reliable? versus reliable?

message priorities? message priorities? multi-site atomic actions? multi-site atomic actions? structured versus byte-stream communication? structured versus byte-stream communication?

communication flexibilitycommunication flexibility can application select and/or modify protocol stacks (statically or can application select and/or modify protocol stacks (statically or

dynamically)?dynamically)? Quality of Service specificationQuality of Service specification

can application specify QoS requirements to network? can application specify QoS requirements to network?

Page 4: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The SOCKET APIThe SOCKET API introduced in 1981 BSD 4.1 UNIXintroduced in 1981 BSD 4.1 UNIX a a host-local, application created/owned, OS-host-local, application created/owned, OS-

controlled interfacecontrolled interface into which application into which application process can both process can both send and receive messagessend and receive messages to/from another (remote or local) application to/from another (remote or local) application processprocess

Page 5: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The SOCKET API (cont)The SOCKET API (cont)

two sockets on separate hosts ``connected'' by OS two sockets on separate hosts ``connected'' by OS socket management routines. Application only sees local socket management routines. Application only sees local socketsocket..

sockets explicitly created, used, released by applicationssockets explicitly created, used, released by applications based on client/server paradigmbased on client/server paradigm two types of transport service via socket API:two types of transport service via socket API:

unreliable datagram unreliable datagram reliable, stream-orientedreliable, stream-oriented

presentation, session layers missing in UNIX networking presentation, session layers missing in UNIX networking (an application concern!).(an application concern!).

Page 6: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Sockets: conceptual viewSockets: conceptual view

each socket has separate send/receive each socket has separate send/receive buffers, port id, parameters (application buffers, port id, parameters (application queryable and setable). queryable and setable).

socket operations implemented as system socket operations implemented as system calls into OScalls into OS

user/kernel boundary crossed: overheaduser/kernel boundary crossed: overhead

Page 7: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Sockets: conceptual viewSockets: conceptual view

buffereddata yetto send

buffereddata yet

to besent

port # socketparameters

USERUSERAPP.APP.

SOCKETSOCKETLAYERLAYER

TRANSPORTTRANSPORTLAYERLAYER

msgsend() bind() msgsrecv() getsockopt()setsocketopt()

?

UserUserspacespace

OperatingOperatingsystemsystem

Page 8: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Connectionless ServiceConnectionless Service

datagram service:datagram service: underlying transport protocols underlying transport protocols do do not guarantee deliverynot guarantee delivery

no explicit identification of who is server, who is clientno explicit identification of who is server, who is client if initiating contact if initiating contact with other side, need to knowwith other side, need to know

IP addressIP address port number of process waiting to be contacted.port number of process waiting to be contacted.

if waiting for contact if waiting for contact from other side, need to declarefrom other side, need to declare port number at which waiting for other sideport number at which waiting for other side

Page 9: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

1.create transport endpoint: socket()

2. assign transport endpoint an address: bind()

3. wait for pkt to arrive: recvfrom()

4. send reply (if any): sendto()

5. release transport endpoint: close()

1. create transport endpoint: socket()

2. assign transport endpoint address: (optional) bind()

3. determine address of server

4. send msg: sendto()

5. wait for pkt to arrive: recvfrom()

6. Release transport endpoint: close()

CLIENT

SERVER

Page 10: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Creating a socketCreating a socket same endpoint (socket) used to send/receive datasame endpoint (socket) used to send/receive data no a priori association of socket with networkno a priori association of socket with network must specify transport protocol family, and specific must specify transport protocol family, and specific

transport-level service to be used with socket: transport-level service to be used with socket:

Protocol Family symbolic nameTCP/IP Internet AF_INETXerox NS AF_NSintra-host UNIX AF_UNIXDEC DNA AF_DECNET

service type symbolic name commentdatagram SOCK_DGRAM UDP protocol in AF_INETreliable, in-order SOCK_STREAM TCP protocol in AF_INETraw socket SOCK_RAW direct access to network

layer

Page 11: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Creating a socket (cont.)Creating a socket (cont.)

int socket ( int family, int service, int protocol)int socket ( int family, int service, int protocol) family is symbolic name of protocol family family is symbolic name of protocol family service is symbolic name of service typeservice is symbolic name of service type protocol allows further specification of raw socket. For us, this will be 0. protocol allows further specification of raw socket. For us, this will be 0. return code from socket() is a socket descriptor, used in all remaining socket-related system return code from socket() is a socket descriptor, used in all remaining socket-related system

callscalls

Example:Example:

#include <sys/types.h>#include <sys/types.h>

#include<sys/ socket.h> #include<sys/ socket.h>

int sockfd; int sockfd;

if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { /* handle error */ } { /* handle error */ }

Page 12: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Internet addressingInternet addressing

each Internet host has one or more globally-each Internet host has one or more globally-unique 32-bit IP addressesunique 32-bit IP addresses

host may have two or more addresseshost may have two or more addresses address associated with each interface card address associated with each interface card

dotted decimal notation: dotted decimal notation: 4 decimal integers, each specifying one byte of IP 4 decimal integers, each specifying one byte of IP

address: address:

host name gaia.cs.umass.edu32-bit address 10000000 01110111 00101000 10111010dotted decimal 128.119.40.186

Page 13: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Internet addressingInternet addressing

library procedure library procedure inet_addr() inet_addr() converts converts dotted-decimal address string to a 32-bit dotted-decimal address string to a 32-bit addressaddress

library procedure library procedure gethostbyname() gethostbyname() converts textual name to dotted-decimal. converts textual name to dotted-decimal.

Page 14: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The Internet Domain System The Internet Domain System StructureStructure

hierarchical administering of nameshierarchical administering of names e.g.: gaia.cs.umass.edue.g.: gaia.cs.umass.edu leftmost name is typically a host name (has an leftmost name is typically a host name (has an

IP address)IP address) next leftmost name is organization next leftmost name is organization

administering that host (e.g., UMass CS Dept.)administering that host (e.g., UMass CS Dept.) next leftmost name is organization next leftmost name is organization

administering all of subnames to the left (e.g., administering all of subnames to the left (e.g., UMass administers cs, ecs, ucs domains)UMass administers cs, ecs, ucs domains)

Page 15: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

rightmost (highest) domain an organization, rightmost (highest) domain an organization, structure, countrystructure, country

domain usage examplecom business watson.ibm.comedu educational cs.umass.edugov US non-military gov't whitehouse.govmil US military arpa.milorg non-profit organization npr.orgnet network resources nis.nsf.netjp Japan osaka-u.ac.jp

Page 16: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

DNS: Internet Domain Name SystemDNS: Internet Domain Name System

a a distributed database distributed database used by TCP/IP applications used by TCP/IP applications to map to/from hostnames from/to IP addressesto map to/from hostnames from/to IP addresses

name servers :name servers : user-level library routines user-level library routines gethostbyname()gethostbyname() and and gethostbyaddress()gethostbyaddress() contact local nameserver via port contact local nameserver via port 5353

name server returns IP address of requested hostnamename server returns IP address of requested hostname

Page 17: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface
Page 18: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

DNS: non-local namesDNS: non-local namesfinding non-local namesfinding non-local names no single name server has complete infono single name server has complete info if local name server can't resolve address, contacts root name if local name server can't resolve address, contacts root name

server:server: 9 redundant root nameservers world-wide9 redundant root nameservers world-wide each has addresses of names servers for all level-two name servers (e.g., each has addresses of names servers for all level-two name servers (e.g.,

umass.edu, ibm.com)umass.edu, ibm.com) contacted root server returns IP address of name server resolver should contacted root server returns IP address of name server resolver should

contactcontact contacted level-two name server may itself return a pointer to another contacted level-two name server may itself return a pointer to another

name server name server name resolution an iterative process of following name server pointersname resolution an iterative process of following name server pointers DNS protocol specifies packet formats for exchanges with DNS serversDNS protocol specifies packet formats for exchanges with DNS servers

Page 19: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Assigning socket a network address: Assigning socket a network address: bind()bind()

each socket must be associated with a local, each socket must be associated with a local, host-unique 16-bit port number. host-unique 16-bit port number.

need to associate socket with globally unique need to associate socket with globally unique network address (host address and port)network address (host address and port) OS knows that incoming messages addressed to OS knows that incoming messages addressed to

this host address and port to be delivered this host address and port to be delivered (demultiplexed to) to this socket(demultiplexed to) to this socket

a return address for outgoing messagesa return address for outgoing messages

Page 20: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Port number(s) comment1 - 255 reserved for standard services21 ftp service23 telnet service25 SMTP email80 http daemon1 - 1023 available only to privileged users1024 - 4999 usable by system and user processes5000 - usable only by user processes

Port NumbersPort Numbers

Page 21: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Socket addressing: predefined Socket addressing: predefined address structuresaddress structures

specifying socket addresses: certain data structures predefined for specifying socket addresses: certain data structures predefined for you:you:

struct sockaddr_in { /* INET socket addr info */ struct sockaddr_in { /* INET socket addr info */

short sin_family; /* set me to AF_INET */ short sin_family; /* set me to AF_INET */

u_short sin_port; /* 16 bit number, nbo */u_short sin_port; /* 16 bit number, nbo */

struct in_addr sin_addr; /* 32 bit host address */ struct in_addr sin_addr; /* 32 bit host address */ char sin_zero[8]; /* not used */char sin_zero[8]; /* not used */

}; };

struct in_addr { struct in_addr {

u_long s_addr; /* 32 bit host addr.,nbo */u_long s_addr; /* 32 bit host addr.,nbo */}; };

Page 22: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The bind() system callThe bind() system call

int bind ( int sockfd, struct sockaddr int bind ( int sockfd, struct sockaddr *myaddr, int addresslen)*myaddr, int addresslen)

sockfdsockfd is the variable assigned socket() return value. is the variable assigned socket() return value. *myaddr:*myaddr: address ofaddress of sockaddr_in structure holding sockaddr_in structure holding

local address info. Must be cast to type sockaddr. local address info. Must be cast to type sockaddr. addresslen addresslen is the size of the address structureis the size of the address structure

error return indicates port number already in use, out-of-error return indicates port number already in use, out-of-

rangerange

Page 23: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The bind() system call (cont)The bind() system call (cont)#include <sys/types.h>#include <sys/types.h>

#include <sys/socket.h>#include <sys/socket.h>

#include "inet.h”#include "inet.h”

int sockfd;int sockfd;

struct sockaddr_in myaddr;struct sockaddr_in myaddr;

if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)

{ /* handle error */ }{ /* handle error */ }

myaddr.sin_family = AF_INET;myaddr.sin_family = AF_INET;

myaddr.sin_port = htons(5100); /* > 5000myaddr.sin_port = htons(5100); /* > 5000

myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_addr.s_addr = htonl(INADDR_ANY);

/* INADDR lets OS determine hostid *//* INADDR lets OS determine hostid */

if ( bind(sockfd, (struct sockaddr *) &myaddr, if ( bind(sockfd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0)sizeof(myaddr)) < 0)

{ /* handle error */ } { /* handle error */ }

Page 24: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Example: connectionless serverExample: connectionless server 1 #include <stdio.h>1 #include <stdio.h>2 #include <sys/types.h> 2 #include <sys/types.h> 3 #include <sys/socket.h> 3 #include <sys/socket.h> 4 #include <netinet/in.h> 4 #include <netinet/in.h> 5 #include <arpa/inet.h> 5 #include <arpa/inet.h> 6 #include <errno.h> 6 #include <errno.h> 7 #define MY_PORT_ID 6090 /* a number > 5000 */ 7 #define MY_PORT_ID 6090 /* a number > 5000 */ 8 8 9 main() 9 main() 10 { 10 { 11 int sockid, nread, addrlen; 11 int sockid, nread, addrlen; 12 struct sockaddr_in my_addr, client_addr; 12 struct sockaddr_in my_addr, client_addr; 13 char msg[50]; 13 char msg[50]; 14 14

Page 25: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

15 printf("Server: creating socket\n"); 15 printf("Server: creating socket\n"); 16 if ( (sockid = socket (AF_INET, SOCK_DGRAM, 0)) < 0){ 16 if ( (sockid = socket (AF_INET, SOCK_DGRAM, 0)) < 0){ 17 printf("Server: socket error: %d\n",errno); 17 printf("Server: socket error: %d\n",errno); 18 exit(0); 18 exit(0); 19 } 19 }

20 printf("Server: binding my local socket\n");20 printf("Server: binding my local socket\n"); 21 bzero((char *) &my_addr, sizeof(my_addr)); 21 bzero((char *) &my_addr, sizeof(my_addr)); 22 my_addr.sin_family = AF_INET; 22 my_addr.sin_family = AF_INET; 23 my_addr.sin_addr.s_addr = htons(INADDR_ANY); 23 my_addr.sin_addr.s_addr = htons(INADDR_ANY); 24 my_addr.sin_port = htons(MY_PORT_ID); 24 my_addr.sin_port = htons(MY_PORT_ID);

Page 26: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Example: connectionless server Example: connectionless server (cont)(cont)

25 if ( (bind(sockid, (struct sockaddr *) &my_addr,25 if ( (bind(sockid, (struct sockaddr *) &my_addr,26 sizeof(my_addr)) < 0) ){26 sizeof(my_addr)) < 0) ){27 printf("Server: bind fail: %d\n",errno);27 printf("Server: bind fail: %d\n",errno);28 exit(0);28 exit(0);29 } 29 } 30 printf("Server: starting blocking message read\n");30 printf("Server: starting blocking message read\n");

31 nread = recvfrom(sockid,msg,11,0, 31 nread = recvfrom(sockid,msg,11,0, 32 (struct sockaddr *) &client_addr, &addrlen); 32 (struct sockaddr *) &client_addr, &addrlen); 33 printf("Server: return code from read is %d\n",nread); 33 printf("Server: return code from read is %d\n",nread); 34 if (nread >0) printf("Server: message is: 34 if (nread >0) printf("Server: message is: %.11s\n",msg);%.11s\n",msg);35 close(sockid); 35 close(sockid); 36 } 36 }

Page 27: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Example: connectionless clientExample: connectionless client

1 #include <stdio.h>1 #include <stdio.h>2 #include <sys/types.h> 2 #include <sys/types.h> 3 #include <sys/socket.h> 3 #include <sys/socket.h> 4 #include <netinet/in.h> 4 #include <netinet/in.h> 5 #include <arpa/inet.h> 5 #include <arpa/inet.h> 6 #include <errno.h> 6 #include <errno.h> 7 #define MY_PORT_ID 6089 7 #define MY_PORT_ID 6089 8 #define SERVER_PORT_ID 6090 8 #define SERVER_PORT_ID 6090 9 #define SERV_HOST_ADDR "128.119.40.186" 9 #define SERV_HOST_ADDR "128.119.40.186" 10 10 11 main() 11 main() 12 { 12 { 13 13 int sockid, retcode; int sockid, retcode; 14 struct sockaddr_in my_addr, server_addr; 14 struct sockaddr_in my_addr, server_addr; 15 char msg[12]; 15 char msg[12];

Page 28: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

161617 printf("Client: creating socket\n"); 17 printf("Client: creating socket\n"); 18 if ((sockid = socket(AF_INET, SOCK_DGRAM, 0)) < 0){ 18 if ((sockid = socket(AF_INET, SOCK_DGRAM, 0)) < 0){ 19 printf("Client: socket failed: %d\n",errno); 19 printf("Client: socket failed: %d\n",errno); 20 exit(0);20 exit(0);21 }21 }22 22 23 printf("Client: binding my local socket\n");23 printf("Client: binding my local socket\n");24 bzero((char *) &my_addr, sizeof(my_addr));24 bzero((char *) &my_addr, sizeof(my_addr));25 my_addr.sin_family = AF_INET; 25 my_addr.sin_family = AF_INET; 26 my_addr.sin_addr.s_addr = htonl(INADDR_ANY); 26 my_addr.sin_addr.s_addr = htonl(INADDR_ANY); 27 my_addr.sin_port = htons(MY_PORT_ID); 27 my_addr.sin_port = htons(MY_PORT_ID); 28 if ( ( bind(sockid, (struct sockaddr *) &my_addr, 28 if ( ( bind(sockid, (struct sockaddr *) &my_addr, 29 sizeof(my_addr)) < 0) ){29 sizeof(my_addr)) < 0) ){30 printf("Client: bind fail: %d\n",errno);30 printf("Client: bind fail: %d\n",errno);31 exit(0); 31 exit(0); 32 } 32 } 3333

Page 29: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

30 printf("Client: creating addr structure for 30 printf("Client: creating addr structure for server\n");server\n");31 bzero((char *) &server_addr, sizeof(server_addr)); 31 bzero((char *) &server_addr, sizeof(server_addr)); 32 server_addr.sin_family = AF_INET; 32 server_addr.sin_family = AF_INET; 33 server_addr.sin_addr.s_addr = 33 server_addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR); inet_addr(SERV_HOST_ADDR); 34 server_addr.sin_port = htons(SERVER_PORT_ID); 34 server_addr.sin_port = htons(SERVER_PORT_ID); 35 35 36 printf("Client: initializing message and 36 printf("Client: initializing message and sending\n"); sending\n"); 37 sprintf(msg, "Hello world"); 37 sprintf(msg, "Hello world"); 38 retcode = sendto(sockid,msg,12,0,(struct 38 retcode = sendto(sockid,msg,12,0,(struct sockaddr *)&server_addr, sizeof(server_addr)); sockaddr *)&server_addr, sizeof(server_addr)); 39 if (retcode <= -1){ 39 if (retcode <= -1){ 40 printf("client: sendto failed: %d\n",errno); 40 printf("client: sendto failed: %d\n",errno); 41 exit(0);41 exit(0);42 } 42 } 43 43 44 /* close socket */ 44 /* close socket */ 45 close(sockid); 45 close(sockid); 46 } 46 }

Page 30: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Example: execution traceExample: execution trace

> cc udpserver.c; mv a.out udpserver > cc udpserver.c; mv a.out udpserver

> cc udpclient.c; mv a.out udpclient > cc udpclient.c; mv a.out udpclient

> udpserver &> udpserver &

[1] 20837[1] 20837

Page 31: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

> Server: creating socketServer: binding my local socketServer: starting blocking message read > udpclientClient: creating socketClient: binding my local socketClient: creating addr structure for server Client: initializing message and sending Server: return code from read is 11Server: message is: Hello world[1] Done udpserver

Page 32: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Connection-oriented serviceConnection-oriented service

Page 33: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

SERVER

assign address assign address to transport endpointto transport endpoint:bind()bind()

CLIENTcreate transportcreate transportendpoint: endpoint: socket()socket()

assign trasnportassign trasnportendpoint an addressendpoint an address(optional) :(optional) :bind()bind()

announce willing toannounce willing toaccept connections: accept connections: listen()listen()

block/wait for block/wait for incoming conn. req.:incoming conn. req.:accept()accept()(new socket (new socket created on return)created on return)

wait for pkt:wait for pkt:recvfrom()recvfrom()

send reply (if any):send reply (if any):sendto()sendto()

connect to server connect to server via socket: via socket: connect()connect()

release transportrelease transportendpointendpoint::close()close()

send msg:send msg: sendto() sendto()

wait for reply:wait for reply:recvfrom()recvfrom()

create transport create transport endpoint:endpoint:socket()socket()for incoming requestsfor incoming requests

release transportrelease transportendpointendpoint::close()close()

determine addr. of serverdetermine addr. of server

msg exchangeand synch.

request

reply

Page 34: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Connection-oriented serviceConnection-oriented service

client/server handshaking: client/server handshaking: client must explicitly connect to server before sending client must explicitly connect to server before sending

or receiving data or receiving data client will not pass client will not pass connect()connect() until server accepts until server accepts

client client server must explicitly accept client before sending or server must explicitly accept client before sending or

receiving data receiving data server will not pass server will not pass accept()accept() until client connect()'s until client connect()'s

connection-oriented service: underlying transport connection-oriented service: underlying transport service is service is reliable, stream-oriented.reliable, stream-oriented.

Page 35: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Client-to-server connection: Client-to-server connection: connect()connect()

client uses client uses connect() connect() to request connect to to request connect to server and communication via socket server and communication via socket

underlying transport protocol (e.g. TCP) begins underlying transport protocol (e.g. TCP) begins connection setup protocol implementing connection setup protocol implementing client/server handshake client/server handshake

connect() connect() returns when server explicitly accepts returns when server explicitly accepts connection, or timeout (no server response)connection, or timeout (no server response)

typically used with reliable transport protocols, but typically used with reliable transport protocols, but also with datagrams also with datagrams

Page 36: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Client-to-server connection: Client-to-server connection: connect()connect()

int connect ( int sockfd, struct sockaddr int connect ( int sockfd, struct sockaddr *toaddrptr, int addresslen)*toaddrptr, int addresslen)

sockfdsockfd:: variable assigned variable assigned socket() socket() return value. return value. Process accepts incoming connections on this socket Process accepts incoming connections on this socket id.id.

*toaddrptr *toaddrptr is address of is address of sockaddr_insockaddr_in structure structure holding server address info. Must be cast to type holding server address info. Must be cast to type sockaddr.sockaddr.

addresslenaddresslen is the size of address structure is the size of address structure

Page 37: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The listen() system callThe listen() system call

used by connection-oriented server used by connection-oriented server let network/OS know server will accept connection let network/OS know server will accept connection

requests requests does does not not block and does block and does notnot wait for request! wait for request! int listen ( int sockfd, int maxwaiting)int listen ( int sockfd, int maxwaiting)

sockfd:sockfd: variable assigned socket() return value. Process variable assigned socket() return value. Process accepts incoming connections on this socket id.accepts incoming connections on this socket id.

maxwaiting: maxwaiting: maximum number of connection requests that maximum number of connection requests that can be queued, waiting for server to do ancan be queued, waiting for server to do an accept().accept(). Typical Typical value is 5. value is 5.

Page 38: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Server-to-client connection: Server-to-client connection: accept()accept()

done by server, after done by server, after listen(). listen(). server will server will accept()accept() connection request via connection request via

specified socket, and return specified socket, and return newly created socket newly created socket for for use in communicating back to accept()'ed client. use in communicating back to accept()'ed client.

server has one socket for accepting incoming server has one socket for accepting incoming connection requests connection requests creates other (new) sockets for communication with clients creates other (new) sockets for communication with clients

server can not selectively server can not selectively accept()accept() connection connection requests requests typically handled FCFS. typically handled FCFS.

Page 39: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

accept(), contaccept(), cont

int accept ( int sockfd, struct sockaddr int accept ( int sockfd, struct sockaddr *fromaddrptr, int *addresslen)*fromaddrptr, int *addresslen)

sockfdsockfd is variable assigned socket() return value. is variable assigned socket() return value. *fromaddrptr *fromaddrptr is address of is address of sockaddr_insockaddr_in structure structure

containing address info of socket that sent this data. A containing address info of socket that sent this data. A returned value.returned value.

addresslen addresslen is size of address structure. A is size of address structure. A value-result value-result argument argument (set before call, reset during call).(set before call, reset during call).

Page 40: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

accept(), contaccept(), cont

struct sockaddr_in other_app_addr;struct sockaddr_in other_app_addr;int sockid, newsockid, addrsize;int sockid, newsockid, addrsize;……addrsize = sizesizeof(other_app_addr));addrsize = sizesizeof(other_app_addr));newsockid = accept(sockfd, (struct sockaddr *)newsockid = accept(sockfd, (struct sockaddr *) &other_app_addr, &addrsize);&other_app_addr, &addrsize); /* newsockid to communicate with client, /* newsockid to communicate with client, sockid to accept more connections */sockid to accept more connections */

Page 41: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

A Simple Timing Application: 1A Simple Timing Application: 1

Client: Client: connect to server connect to server send server client local timesend server client local time read back server's local timeread back server's local time

Server: Server: receive connections from clients receive connections from clients print out client's local timeprint out client's local time send client server's local timesend client server's local time

Page 42: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

A Simple Timing Application: client A Simple Timing Application: client codecode

1 #include <sys/types.h>1 #include <sys/types.h>2 #include <sys/socket.h>2 #include <sys/socket.h>3 #include <netinet/in.h>3 #include <netinet/in.h>4 #include <arpa/inet.h>4 #include <arpa/inet.h>5 #include <time.h>5 #include <time.h>6 #include <errno.h>6 #include <errno.h>7 #define SERV_HOST_ADDR "128.119.40.186" /* Don's host 7 #define SERV_HOST_ADDR "128.119.40.186" /* Don's host machine */machine */

8 main()8 main()9 {9 {10 int sockid;10 int sockid;11 struct sockaddr_in ssock_addr;11 struct sockaddr_in ssock_addr;12 struct timeval tp;12 struct timeval tp;13 struct timezone tzp; 13 struct timezone tzp; 1414

Page 43: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

15 /* create a socket */15 /* create a socket */16 if ( (sockid = socket(AF_INET, SOCK_STREAM, 0)) < 0){16 if ( (sockid = socket(AF_INET, SOCK_STREAM, 0)) < 0){17 printf("error creating client 17 printf("error creating client socket,error%d\n",errno);socket,error%d\n",errno);18 exit(0); 18 exit(0); 19 }19 }202021 printf("Client: creating addr structure for server\n");21 printf("Client: creating addr structure for server\n");22 bzero((char *) &server_addr, sizeof(server_addr)); 22 bzero((char *) &server_addr, sizeof(server_addr)); 23 server_addr.sin_family = AF_INET; 23 server_addr.sin_family = AF_INET; 24 server_addr.sin_addr.s_addr = 24 server_addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR); inet_addr(SERV_HOST_ADDR); 25 server_addr.sin_port = htons(SERVER_PORT_ID); 25 server_addr.sin_port = htons(SERVER_PORT_ID); 26 if (connect(sockid, (struct sockaddr *) 26 if (connect(sockid, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0){&server_addr, sizeof(server_addr)) < 0){

27 printf("error connecting to server, error: %d\n",errno); 27 printf("error connecting to server, error: %d\n",errno); 28 exit(0);28 exit(0);

29 }29 }

Page 44: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

30 /* send time of day */30 /* send time of day */31 gettimeofday(&tp,&tzp);31 gettimeofday(&tp,&tzp);32 /* convert from host byte order to network 32 /* convert from host byte order to network byte order */byte order */33 printf("client: local time is %ld\n",tp.tv_sec);33 printf("client: local time is %ld\n",tp.tv_sec);34 tp.tv_sec = htonl(tp.tv_sec);34 tp.tv_sec = htonl(tp.tv_sec);35 tp.tv_usec = htonl(tp.tv_usec);35 tp.tv_usec = htonl(tp.tv_usec);38 /* send time of day to other side */38 /* send time of day to other side */39 write(sockid, &tp, sizeof(tp));39 write(sockid, &tp, sizeof(tp));40 /* get time of day back fro other side and display */40 /* get time of day back fro other side and display */41 if ( (read(sockid, &tp, sizeof(tp))) < 0){41 if ( (read(sockid, &tp, sizeof(tp))) < 0){42 printf("error reading new socket\n"); 42 printf("error reading new socket\n"); 43 exit(0); 43 exit(0); 44 }44 }4545

Page 45: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

46 /* convert from network byte order to host byte order */46 /* convert from network byte order to host byte order */47 tp.tv_sec = ntohl(tp.tv_sec);47 tp.tv_sec = ntohl(tp.tv_sec);48 tp.tv_usec = ntohl(tp.tv_usec);48 tp.tv_usec = ntohl(tp.tv_usec);49 printf("client: remote time is %ld\n",tp.tv_sec);49 printf("client: remote time is %ld\n",tp.tv_sec);50 close(sockid); 50 close(sockid); 51 }51 }

Page 46: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Simple Timing Application: server codeSimple Timing Application: server code

1 #include <stdio.h>1 #include <stdio.h>2 #include <sys/types.h>2 #include <sys/types.h>3 #include <sys/socket.h>3 #include <sys/socket.h>4 #include <netinet/in.h>4 #include <netinet/in.h>5 #include <arpa/inet.h>5 #include <arpa/inet.h>6 #include <time.h>6 #include <time.h>7 #include <errno.h>7 #include <errno.h>8 #define MY_PORT_ID 6090 /* a number > 5000 */8 #define MY_PORT_ID 6090 /* a number > 5000 */9910 main()10 main()11 {11 {12 int sockid, newsockid, i,j;12 int sockid, newsockid, i,j;13 struct sockaddr_in ssock_addr;13 struct sockaddr_in ssock_addr;14 struct timeval tp;14 struct timeval tp;15 struct timezone tzp;15 struct timezone tzp;1616

Page 47: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

17 /* create a socket *17 /* create a socket *18 if ( (sockid = socket (AF_INET, SOCK_STREAM, 0)) < 0)18 if ( (sockid = socket (AF_INET, SOCK_STREAM, 0)) < 0)19 { printf("error creating socket, error: %d\n",errno); 19 { printf("error creating socket, error: %d\n",errno); exit(0);}exit(0);}20 /* do a man on errno to get error information */20 /* do a man on errno to get error information */21 /* name the socket using wildcards */21 /* name the socket using wildcards */22 bzero((char *) &ssock_addr, sizeof(ssock_addr));\22 bzero((char *) &ssock_addr, sizeof(ssock_addr));\23 ssock_addr.sin_family = AF_INET;\23 ssock_addr.sin_family = AF_INET;\24 ssock_addr.sin_addr.s_addr = htonl(INADDR_ANY);24 ssock_addr.sin_addr.s_addr = htonl(INADDR_ANY);25 ssock_addr.sin_port = htons(MY_PORT_ID);25 ssock_addr.sin_port = htons(MY_PORT_ID);26 /* bind the socket to port address */26 /* bind the socket to port address */27 if ( ( bind(sockid, (struct sockaddr *) &ssock_addr, 27 if ( ( bind(sockid, (struct sockaddr *) &ssock_addr, sizeof(ssock_addr)) < 0) )sizeof(ssock_addr)) < 0) )28 { printf("error binding socket, error: %d\n",errno);28 { printf("error binding socket, error: %d\n",errno); exit(0); } exit(0); } 29 /* start accepting connections */ 29 /* start accepting connections */ 30 if ( listen (sockid, 5) < 0)30 if ( listen (sockid, 5) < 0)31 { printf("error listening: %d\n",errno); exit(0); }31 { printf("error listening: %d\n",errno); exit(0); }3232

Page 48: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

33 for (i=1; i<=50000 ;i++) {33 for (i=1; i<=50000 ;i++) {34 /* accept a connection */34 /* accept a connection */35 newsockid = accept(sockid, (struct sockaddr *)0,35 newsockid = accept(sockid, (struct sockaddr *)0, (int *)0);(int *)0);36 if (newsockid < 0)36 if (newsockid < 0)37 { printf("error accepting socket, error: 37 { printf("error accepting socket, error: %d\n",errno); exit(0); }%d\n",errno); exit(0); }38 /* read remote time of day from socket */38 /* read remote time of day from socket */39 if ( (read(newsockid, &tp, sizeof(tp))) < 0)39 if ( (read(newsockid, &tp, sizeof(tp))) < 0)40 { printf("error reading new socket\n"); exit(0); }40 { printf("error reading new socket\n"); exit(0); }41 /* convert from network byte order to host byte 41 /* convert from network byte order to host byte order */order */42 tp.tv_sec = ntohl(tp.tv_sec);42 tp.tv_sec = ntohl(tp.tv_sec);43 tp.tv_usec = ntohl(tp.tv_usec);43 tp.tv_usec = ntohl(tp.tv_usec);44 printf("server: remote time is %ld\n",tp.tv_sec);44 printf("server: remote time is %ld\n",tp.tv_sec);4545

Page 49: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

46 /* get local time of day and send to client*/46 /* get local time of day and send to client*/

47 for (j=0; j<1000000; j++)47 for (j=0; j<1000000; j++)

48 ; /* delay */48 ; /* delay */

49 gettimeofday(&tp,&tzp);49 gettimeofday(&tp,&tzp);

50 /* convert from host byte order to network byte50 /* convert from host byte order to network byte order */order */

51 printf("server: local time is %ld\n",tp.tv_sec);51 printf("server: local time is %ld\n",tp.tv_sec);

52 tp.tv_sec = htonl(tp.tv_sec);52 tp.tv_sec = htonl(tp.tv_sec);

53 tp.tv_usec = htonl(tp.tv_usec);53 tp.tv_usec = htonl(tp.tv_usec);

54 write(newsockid, &tp, sizeof(tp));54 write(newsockid, &tp, sizeof(tp));

55 close(newsockid);55 close(newsockid);

56 }56 }

57 close(sockid);57 close(sockid);

58 }58 }

Page 50: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Typical server Typical server structurestructure

Page 51: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Server Structure: code fragmentServer Structure: code fragment

int sockfd, newsockfd;int sockfd, newsockfd; if ( (sockfd = socket( ... )) < 0) /* create socket */ if ( (sockfd = socket( ... )) < 0) /* create socket */..........if ( bind(sockfd,... ) < 0) /* bind socket */if ( bind(sockfd,... ) < 0) /* bind socket */..........if ( listen(sockfd,5) < 0) /* announce we're ready */if ( listen(sockfd,5) < 0) /* announce we're ready */..........while (1==1) { /* loop forever */while (1==1) { /* loop forever */ newsockfd = accept(sockfd, ...); /* wait for client */ newsockfd = accept(sockfd, ...); /* wait for client */

Page 52: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

if ( (pid = fork()) == 0) { if ( (pid = fork()) == 0) { /* child code begins here */ /* child code begins here */ close(sockfd); /* child doesn't wait for client */ close(sockfd); /* child doesn't wait for client */ ...... ...... /* child does work here, communicating /* child does work here, communicating

with client using the newsockfd */with client using the newsockfd */ ....... ....... exit(0); /* child dies here */ exit(0); /* child dies here */ } } /* parent continues execution below */ /* parent continues execution below */ close(newsockfd); /* parent won't communicate with */ close(newsockfd); /* parent won't communicate with */ /* client - that's childsplay! */ /* client - that's childsplay! */ } /* end of while */ } /* end of while */

Page 53: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Sending and Receiving DataSending and Receiving Data

data sent/received using standard UNIX i/o data sent/received using standard UNIX i/o system calls or network-specific system calls system calls or network-specific system calls

system call device buffering options specifypeer?

read()/write() any i/o single N Nreadv()/writev() any i/o scatter/gather N Nrecv()/send() socket single Y Nrecvfrom()/sendto() socket single Y Yrecvmsg()/sendmsg() socket scatter/gather Y Y

Page 54: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

sendto()sendto()

int sendto (int sockfd, char *buff, int bufflen, int int sendto (int sockfd, char *buff, int bufflen, int flags, struct sockaddr *toaddrptr, int addresslen)flags, struct sockaddr *toaddrptr, int addresslen)

sockfd is the variable assigned socket() return value.sockfd is the variable assigned socket() return value. *buff is a set of consecutive mem. locs. holding message to send*buff is a set of consecutive mem. locs. holding message to send bufflen is number of bytes to sendbufflen is number of bytes to send flags can be used to specify options. Always 0 for us.flags can be used to specify options. Always 0 for us. *toaddrptr is address of sockaddr_in structure holding destination *toaddrptr is address of sockaddr_in structure holding destination

address info. Must be cast to type sockaddr.address info. Must be cast to type sockaddr. addresslen is the size of the address structureaddresslen is the size of the address structure OK return code does NOT imply data correctly delivered, only correctly OK return code does NOT imply data correctly delivered, only correctly

sent sent

Page 55: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Example: using sendto()Example: using sendto()

char buffer[50];char buffer[50];struct sockaddr_in other_app_addr;struct sockaddr_in other_app_addr;int retcode int retcode

/* suppose we have done socket() and bind() /* suppose we have done socket() and bind() calls, filled in other_app_addr,and put 23 calls, filled in other_app_addr,and put 23 bytes of data into buffer */bytes of data into buffer */

retcode = sendto(sockfd, buffer, 23, 0, retcode = sendto(sockfd, buffer, 23, 0, (struct sockaddr *) &other_app_addr,(struct sockaddr *) &other_app_addr,sizeof(other_app_addr))sizeof(other_app_addr))

Page 56: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

recvfrom()recvfrom()

int recvfrom (int sockfd, char *buff, int bufflen, int recvfrom (int sockfd, char *buff, int bufflen, int flags, struct sockaddr *fromaddrptr, int int flags, struct sockaddr *fromaddrptr, int *addresslen)*addresslen)

sockfd is variable assigned socket() return value.sockfd is variable assigned socket() return value. *buff is a set of consecutive mem. locs. into which received data to *buff is a set of consecutive mem. locs. into which received data to

be writtenbe written bufflen is number of bytes to readbufflen is number of bytes to read flags can be used to specify options. Always 0 for us.flags can be used to specify options. Always 0 for us. *fromaddrptr is address of sockaddr_in structure containing address *fromaddrptr is address of sockaddr_in structure containing address

info of socket that sent this data. A returned value.info of socket that sent this data. A returned value. addresslen is size of address structure. A returned value.addresslen is size of address structure. A returned value.

recvfrom() returns number bytes actually received recvfrom() returns number bytes actually received

Page 57: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Example: using recvfrom()Example: using recvfrom()

char buffer[50];char buffer[50];struct sockaddr_in other_app_addr;struct sockaddr_in other_app_addr;int nread, addrlen;int nread, addrlen;

/* suppose we have done socket(), bind() */ /* suppose we have done socket(), bind() */nread = recvfrom(sockfd, buffer, 23, 0, nread = recvfrom(sockfd, buffer, 23, 0, (struct sockaddr *) &other_app_addr, (struct sockaddr *) &other_app_addr,

&addrlen))&addrlen))

Page 58: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Scatter read and gather writeScatter read and gather write

used to read/write into/from multiple non-contiguous buffersused to read/write into/from multiple non-contiguous buffers writev(int sd, struct iovec iov[], int writev(int sd, struct iovec iov[], int iovcount);iovcount);

readv(int sd, struct iovec iov[], intreadv(int sd, struct iovec iov[], int iovcount);iovcount); struct iovec{struct iovec{ caddr_t iov_base; /* starting addr ofcaddr_t iov_base; /* starting addr of this buffer */ this buffer */ int iov_len; /* num. bytes in this int iov_len; /* num. bytes in this

buffer */buffer */ }; };

Page 59: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface
Page 60: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Byte Ordering RoutinesByte Ordering Routines

byte ordering routines: convert to/from host 16- and byte ordering routines: convert to/from host 16- and 32-bit integers from/to ``network byte order'' 32-bit integers from/to ``network byte order'' different computers may store bytes of integer in different computers may store bytes of integer in

different order in memory.different order in memory. internal representation of 2^{24}internal representation of 2^{24} network byte order is big-endiannetwork byte order is big-endian integer quantities (such as addressing info) should be integer quantities (such as addressing info) should be

explicitly converted to/from network byte order (nbo). explicitly converted to/from network byte order (nbo).

Page 61: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Big Endian/Little EndianBig Endian/Little Endian

Page 62: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

UNIX ProceduresUNIX Procedures

Functionname

action

htonl convert 32-bit host format to nbo

ntohl convert nbo to 32-bit host format

htons convert 16-bit host format to nbo

ntohs convert nbo to 16-bit host format

Page 63: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Aside: other useful system calls and Aside: other useful system calls and routinesroutines

close(sockfd)close(sockfd) will release a socketwill release a socket getsockopt()getsockopt() andand setsockopt()setsockopt()

system calls used to query/set socket system calls used to query/set socket options.options.

ioctl()ioctl() system call used to query/set system call used to query/set socket attributes, also network device socket attributes, also network device interface attributes.interface attributes.

Page 64: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Asynchronous I/OAsynchronous I/O

socket reads we have seen are blocking. socket reads we have seen are blocking. application can be notified by OS when data application can be notified by OS when data

ready to be read using asynchronous i/o:ready to be read using asynchronous i/o: write a ``handler'' procedure: called by OS when write a ``handler'' procedure: called by OS when

data ready to be readdata ready to be read inform OS of process id and name of procedure to inform OS of process id and name of procedure to

be calledbe called enable asynchronous i/oenable asynchronous i/o

Page 65: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

Asynchronous I/O: exampleAsynchronous I/O: example

#include <signal.h>#include <signal.h>

#include <fnctl.h>#include <fnctl.h>

int datahere = 0;int datahere = 0;

main() {main() { /* create, bind, connect/accept, etc done /* create, bind, connect/accept, etc done

here */here */signal(SIGIO,read_proc); signal(SIGIO,read_proc); /* inform OS: call read_proc when data /* inform OS: call read_proc when data

arrives */arrives */fnctl(sd, F_SETOWN, getpid())fnctl(sd, F_SETOWN, getpid()) /* inform OS: procedure is inside ``me'' *//* inform OS: procedure is inside ``me'' */fnctl(sd, F_SETFL, FASYNCH)fnctl(sd, F_SETFL, FASYNCH) /* enable asynchronous I/O *//* enable asynchronous I/O */

Page 66: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

while (1==1) {while (1==1) { ..… ..…

/ * do useful work, possibly checking datahere / * do useful work, possibly checking datahere flag. Note there is NO EXPLICIT CALL to read_proc() flag. Note there is NO EXPLICIT CALL to read_proc() */*/

}} }} read_proc() /* called by OS on data arrivalread_proc() /* called by OS on data arrival */*/{{

datahere = 1;datahere = 1; /* possibly do other useful work */ /* possibly do other useful work */

}}

Page 67: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The select() system callThe select() system call

application may want to respond to incoming i/o (e.g., application may want to respond to incoming i/o (e.g., data, connect requests) occurring on several different data, connect requests) occurring on several different socketsocket

do not want to block on any single, accept(), recvmsg()do not want to block on any single, accept(), recvmsg() I/O multiplexing using select(): I/O multiplexing using select():

inform OS of set of sockets we're interested ininform OS of set of sockets we're interested in call select(), which won't return until I/O pending on one of call select(), which won't return until I/O pending on one of

specified socketsspecified sockets select() will tell us which sockets are ready for I/Oselect() will tell us which sockets are ready for I/O do I/O (e.g., accept(), recvmsg()) on appropriate socketdo I/O (e.g., accept(), recvmsg()) on appropriate socket

Page 68: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The select() system callThe select() system call

macros FD_ZERO, FD_SET, FD_CLEAR, macros FD_ZERO, FD_SET, FD_CLEAR, FD_ISSET supplied by OS, used by application FD_ISSET supplied by OS, used by application for declaring, determining ready socket(s). for declaring, determining ready socket(s).

int select(int maxsockets, fd_set int select(int maxsockets, fd_set *readytoread,*readytoread, fd_set *readytowrite, fd_set fd_set *readytowrite, fd_set *readyexceptions,*readyexceptions, struct timeval *timeptr); struct timeval *timeptr);

Page 69: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The select() system call: simple The select() system call: simple exampleexample

#include <sys/types.h>#include <sys/types.h> main(){main(){ fd_set readset;fd_set readset; int nready; int nready; /* open, bind, connect/accept etc. sockets /* open, bind, connect/accept etc. sockets sd1, sd2, sd3 */sd1, sd2, sd3 *//* tell OS sockets we're interested in *//* tell OS sockets we're interested in */FD_ZERO(&readset);FD_ZERO(&readset);FD_SET(sd1,&readset);FD_SET(sd1,&readset);FD_SET(sd2,&readset);FD_SET(sd2,&readset);FD_SET(sd3,&readset);FD_SET(sd3,&readset);

Page 70: Network Application Programming Introduction: issues Sockets: programming and implementation Other API’s:  winsock  java  transport layer interface

The select() system call: simple The select() system call: simple exampleexample

/* call select, returning when /* call select, returning when something's ready */something's ready */nready = select(64, &readset, NULL, nready = select(64, &readset, NULL, NULL, NULL);NULL, NULL);/* read from appropriate socket *//* read from appropriate socket */if (FD_ISSET(sd1, &readset)) if (FD_ISSET(sd1, &readset)) ..... /* do i/o from sd1 */..... /* do i/o from sd1 */else if (FD_ISSET(sd2, &readset)) else if (FD_ISSET(sd2, &readset)) ..... /* do i/o from sd2 */..... /* do i/o from sd2 */else if (FD_ISSET(sd3, &readset)) else if (FD_ISSET(sd3, &readset)) ..... /* do i/o from sd3 */..... /* do i/o from sd3 */