Download presentation
Presentation is loading. Please wait.
Published byOliver Stewart Modified over 9 years ago
1
Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon
2
Client/Server Programming Client/Server Programming Outline What is a socket and what are the two types?What is a socket and what are the two types? The layered network modelThe layered network model Client/server model and types of serversClient/server model and types of servers Internet addressingInternet addressing Basic socket callsBasic socket calls Sample client and serverSample client and server
3
Client/Server Programming What is a socket? A way to communicate to other programs using a descriptor that is like a file descriptor. You must open itopen it read/write or send/recvread/write or send/recv close itclose it Sockets
4
Client/Server Programming Two Types of Sockets Stream sockets (a.k.a., TCP)Stream sockets (a.k.a., TCP) Datagram sockets (a.k.a., UDP)Datagram sockets (a.k.a., UDP) The sockets library that we will use is actually very flexible, and supports many types of communication Sockets
5
Client/Server Programming TCP Sockets TCP = Transmission Control Protocol reliable, connection-orientedreliable, connection-oriented two-way connectiontwo-way connection messages sent in order arrive in ordermessages sent in order arrive in order like the telephone system Sockets
6
Client/Server Programming TCP Sockets A connection must be established between the sender and the receiverA connection must be established between the sender and the receiver A conversation takes placeA conversation takes place The connection must be endedThe connection must be ended Sockets
7
Client/Server Programming TCP Sockets Applications FTP = File Transfer ProtocolFTP = File Transfer Protocol HTTP = HyperText Transfer ProtocolHTTP = HyperText Transfer Protocol SMTP = Simple Mail Transfer ProtocolSMTP = Simple Mail Transfer Protocol... are all built over TCP... are all built over TCP Sockets
8
Client/Server Programming The top half of TCP/IP IP = Internet Protocol is the protocol that ties all computers (devices) on the Internet togetheris the protocol that ties all computers (devices) on the Internet together TCP is a transport layer protocol built over IPTCP is a transport layer protocol built over IP Sockets
9
Client/Server Programming UDP Sockets UDP = User Datagram Protocol connectionless, unreliableconnectionless, unreliable communication is not guaranteed to arrive, and may not arrive in ordercommunication is not guaranteed to arrive, and may not arrive in order like the post office Sockets
10
Client/Server Programming UDP Sockets Don’t require set up or tear down of a connectionDon’t require set up or tear down of a connection Generally used for packet-by-packet transfers of informationGenerally used for packet-by-packet transfers of information UDP applications include TFTP, BOOTPUDP applications include TFTP, BOOTP Sockets
11
Client/Server Programming User Datagram Protocol UDP is also a transport layer protocol built over IPUDP is also a transport layer protocol built over IP Generally, UDP applications implement acknowledgements to ensure that the packets arrive. (TCP does this for you so you don’t have to!)Generally, UDP applications implement acknowledgements to ensure that the packets arrive. (TCP does this for you so you don’t have to!) Sockets
12
Client/Server Programming The Layered Network Model Physical (e.g., cables, etc.) Data Link (e.g., Ethernet) Network (e.g., IP) Transport (e.g., TCP, UDP) Application (e.g., FTP, HTTP, telnet) Network Model
13
Client/Server Programming When a message is sent The application constructs a messageThe application constructs a message user data Network Model
14
Client/Server Programming When a message is sent The message is packaged (encapsulated) with a header from the transport layer (e.g., TCP) and sent to the network layerThe message is packaged (encapsulated) with a header from the transport layer (e.g., TCP) and sent to the network layer user dataTCP Network Model
15
Client/Server Programming When a message is sent The network layer adds a headerThe network layer adds a header user dataTCPIP An IP packet Network Model
16
Client/Server Programming When a message is sent The data link layer adds a header, and the frame is sent out on the networkThe data link layer adds a header, and the frame is sent out on the network user dataTCPIPEthernet An Ethernet frame Network Model
17
Client/Server Programming When a message is sent Application builds message in user memory Message is copied to kernel and TCP/IP and Ethernet headers are added Message is sent onto network to receiver Message is copied to kernel and TCP/IP and Ethernet headers are stripped Message arrives to user memory and the application is notified You only see the communication at THIS LEVEL Message arrives to user memory and the application is notified Network Model
18
Client/Server Programming Client/Server Model Starts first Waits for contact from a client Responds to requests Starts second Contacts a server with a request Waits for response from server ServerClient Client/Server Model
19
Client/Server Programming Types of Servers A server can be: Types of Servers Stateful Stateless IterativeConcurrent iterative stateful concurrent stateful iterative stateless concurrent stateless
20
Client/Server Programming Stateful Server Maintains some information between requestsMaintains some information between requests Requires smaller messages, since some information is kept between contactsRequires smaller messages, since some information is kept between contacts May become confused if a connection terminates abnormally (if the design is not fault tolerant)May become confused if a connection terminates abnormally (if the design is not fault tolerant) Example: FTPExample: FTP Types of Servers
21
Client/Server Programming Stateless Server Requires larger messages. That is, the message must contain all information about the request since no state information is kept.Requires larger messages. That is, the message must contain all information about the request since no state information is kept. Example: HTTPExample: HTTP Types of Servers
22
Client/Server Programming Iterative Server while (1) { accept a connection (or request) accept a connection (or request) from a client from a client service the client service the client close the connection (if necessary) close the connection (if necessary)} Types of Servers
23
Client/Server Programming Concurrent Server while (1) { accept a connection/request from client accept a connection/request from client start a new thread to handle this client start a new thread to handle this client /* the thread must close the connection! */ /* the thread must close the connection! */} Types of Servers
24
Client/Server Programming Internet Addressing Suppose you type:Suppose you type: http://comp.uark.edu/~aapon http://comp.uark.edu/~aapon This invokes the HTTP protocol (over TCP/IP), and the computer “comp.uark.edu” is sent a messageThis invokes the HTTP protocol (over TCP/IP), and the computer “comp.uark.edu” is sent a message Addressing
25
Client/Server Programming Internet Addressing http://comp.uark.edu/~aapon/ Same as IP address 130.184.252.197Same as IP address 130.184.252.197 Find the home page of user aapon Contact the HTTP server on the computer named comp.uark.edu Addressing
26
Client/Server Programming Internet Addressing A Domain Name Server (DNS) may be called to find the IP address of comp.uark.eduA Domain Name Server (DNS) may be called to find the IP address of comp.uark.edu Each IP machine is usually configured with the name of a DNS server.Each IP machine is usually configured with the name of a DNS server. Some IP names and addresses can also be stored in /etc/hostfileSome IP names and addresses can also be stored in /etc/hostfile Addressing
27
Client/Server Programming Internet Addressing “http” says: send the message to port 80 An IP address includes both a host address and a port number!An IP address includes both a host address and a port number! The HTTP server listens to port 80The HTTP server listens to port 80 The HTTP server responds when a client contacts itThe HTTP server responds when a client contacts it Addressing
28
Client/Server Programming Internet Addressing You can write a server that listens to any port not already in use! A port number is a 16-bit integer. Ports below 1024 are reserved for system use.A port number is a 16-bit integer. Ports below 1024 are reserved for system use. Well-known ports include FTP, Telnet, SMTP, etc.Well-known ports include FTP, Telnet, SMTP, etc. Addressing
29
Client/Server Programming Basic Socket Calls struct sockaddr, htonsstruct sockaddr, htons Server calls: socket, bind, listen, accept, recv, send, closeServer calls: socket, bind, listen, accept, recv, send, close Client calls: socket, connect, send, recv, closeClient calls: socket, connect, send, recv, close gethostbyname, getprotobynamegethostbyname, getprotobyname Socket Calls
30
Client/Server Programming A Socket Descriptor just an intjust an int int sd; int sd; It will point to a socket structure in memory Socket Calls
31
Client/Server Programming Create a socket socket()socket() –Returns a socket descriptor that you can use in later sockets calls (equivalent to fopen() for files) sd = socket(AF_INET, SOCK_STREAM, 0) protocoldomaintype Socket Calls
32
Client/Server Programming Socket Address Structure struct sockaddr { unsigned short sa_family; unsigned short sa_family; char sa_data[14]; char sa_data[14];}; address family AF_INET 14 bytes of protocol address Socket Calls
33
Client/Server Programming Socket Address for Internet struct sockaddr_in { /* for convenience */ short int sin_family; short int sin_family; unsigned short int sin_port; /* 2 bytes */ unsigned short int sin_port; /* 2 bytes */ struct in_addr sin_addr;/* 4 bytes */ struct in_addr sin_addr;/* 4 bytes */ unsigned char sin_zero[8]; unsigned char sin_zero[8];}; Socket Calls
34
Client/Server Programming Watch out for Endians! The sin_port and sin_address must be in Network Byte Order, which is (possibly) different from Host Byte OrderThe sin_port and sin_address must be in Network Byte Order, which is (possibly) different from Host Byte Order Conversion routines include:Conversion routines include: –htons - “Host to Network Short” –htonl - “Host to Network Long” Also ntohs and ntohl Socket Calls
35
Client/Server Programming The Server Calls Bind() int sd; struct sockaddr_in my_addr; sd = socket(AF_INET, SOCK_STREAM, 0); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(MYPORT); /* use 0 for default */ my_addr.sin_addr.s_addr=INADDR_ANY; /* is really 0 */ bzero(&(my_addr.sin_zero), 8); bind(sd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)); typecastsize of the addressdescriptor Socket Calls
36
Client/Server Programming Bind() Finishes filling the socket structure with address and port information in the serverFinishes filling the socket structure with address and port information in the server Specifies the port that the server will listen toSpecifies the port that the server will listen to Largest port allowed isLargest port allowed is 65535 Socket Calls
37
Client/Server Programming The Server Calls listen() #define QLEN 6 #define QLEN 6 listen(sd, QLEN); listen(sd, QLEN); socket descriptor maximum number of requests that can be queued Listen is NOT a blocking call! Socket Calls
38
Client/Server Programming The Server Calls accept() accept() is a blocking call! sin_size = sizeof(struct sockaddr_in); sin_size = sizeof(struct sockaddr_in); nsd = accept(sd, &their_addr, &sin_size); nsd = accept(sd, &their_addr, &sin_size); nsd is a new descriptor -- send/recv on it old sd is still there, and can be used again Socket Calls
39
Client/Server Programming A Typical Iterative Server socket();bind();listen(); while(1) { accept(); accept(); /* do some work with the client */ /* do some work with the client */ close(); close();} Block here, waiting for a connection! Socket Calls
40
Client/Server Programming The Client Calls connect() struct sockaddr_in dest_addr; sd = socket(AF_INET, SOCK_STREAM, 0); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(DEST_PORT); dest_addr.sin_addr.s_addr = inet_addr(DEST_IP); bzero(&(dest_addr.sin_zero), 8); connect(sd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr)); Socket Calls
41
Client/Server Programming Sending char *msg = “Amy was here!"; int len, bytes_sent; len = strlen(msg); bytes_sent = send(sd, msg, len, 0); flags Socket Calls
42
Client/Server Programming Receiving Stream Sockets numbytes = recv(sd, buf, BUFSIZE, 0); while(numbytes>0) { buf[numbytes] = ‘\0’; buf[numbytes] = ‘\0’; printf(“%s”, buf); printf(“%s”, buf); numbytes = recv(sd, buf, BUFSIZE, 0); numbytes = recv(sd, buf, BUFSIZE, 0);} Socket Calls
43
Client/Server Programming Close the Socket close(sd); Closes the open socketCloses the open socket Frees memory and allows the socket descriptor to be re-used for a different socketFrees memory and allows the socket descriptor to be re-used for a different socket Socket Calls
44
Client/Server Programming Utility Functions Gethostbyname()Gethostbyname() –Does a DNS call, if necessary. Converts an IP name to an IP address Getprotobyname()Getprotobyname() –Returns a pointer to a protocol table entry, to be sure that TCP (or UCP) is known Socket Calls
45
Client/Server Programming /* To compile me in Solaris, type: gcc -o client client.c -lsocket -lnsl */ /* To compile me in Linux, type: gcc -o client client.c */ /* client.c - code for example client that uses TCP */ /* From Computer Networks and Internets by Douglas F. Comer */ #include #define closesocket close #define PROTOPORT 5193 /* default protocol port number */ Example Client
46
Client/Server Programming extern int errno; char localhost[] = "localhost"; /* default host name */ /*--------------------------------------------------------------------- * Program: client * * Purpose: allocate a socket, connect to a server, and print all output * * Syntax: client [ host [port] ] * * host - name of a computer on which server is executing * port - protocol port number server is using * * Note: Both arguments are optional. If no host name is specified, * the client uses "localhost"; if no protocol port is * specified, the client uses the default given by PROTOPORT. * *--------------------------------------------------------------------- */ Example Client
47
Client/Server Programming main(int argc, char *argv[]) { struct hostent *ptrh; /* pointer to a host table entry */ struct protoent *ptrp; /* point to a protocol table entry */ struct sockaddr_in sad; /* structure to hold server's address */ int sd; /* socket descriptor */ int port; /* protocol port number */ char *host; /* pointer to host name */ int n; /* number of characters read */ char buf[1000]; /* buffer for data from the server */ memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */ sad.sin_family = AF_INET; /* set family to Internet */ /* Check command-line argument for protocol port and extract */ /* port number if on is specified. Otherwise, use the default */ /* port value biven by constant PROTOPORT */ Example Client
48
Client/Server Programming if (argc > 2) port = atoi(argv[2]); else port = PROTOPORT; if (port > 0) sad.sin_port = htons((u_short)port); else { fprintf( stderr,"bad port number %s\n", argv[2]); exit(1); } if (argc > 1 ) host = argv[1]; else host = localhost; ptrh = gethostbyname(host); if( ((char *)ptrh) == NULL) { fprintf( stderr, "invalid host: %s\n", host); exit(1); } Example Client
49
Client/Server Programming memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length); if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) { fprintf( stderr, "cannot map \"tcp\" to protocol number\n"); exit(1); } sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto); if (sd < 0) { fprintf( stderr, "socket creation failed\n"); exit(1); } if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) { fprintf( stderr, "connect failed\n"); exit(1); } Example Client
50
Client/Server Programming n = recv(sd, buf, sizeof(buf), 0); while(n > 0) { buf[n] = '\0'; printf("CLIENT: %s", buf); n = recv(sd, buf, sizeof(buf), 0); } closesocket(sd); exit(0); } Example Client
51
Client/Server Programming /* to compile me on Solaris, type: gcc -o server server.c -lsocket -lnsl */ /* to compile me in Linux, type: gcc -o server server.c */ /* server.c - code for example server program that uses TCP */ /* From Computer Networks and Internets by Douglas F. Comer */ #define closesocket close #include #define PROTOPORT 5193 /* default protocol port number */ #define QLEN 6 /* size of request queue */ int visits = 0; /* counts client connections */ Example Server
52
Client/Server Programming /*---------------------------------------------------------------------------- * Program: server * * Purpose: allocate a socket and then repeatedly execute the folllowing: * (1) wait for the next connection from a client * (2) send a short message to the client * (3) close the connection * (4) go back to step (1) * * Syntax: server [ port ] * * port - protocol port number to use * * Note: The port argument is optional. If no port is specified, * the server uses the default given by PROTOPORT. * *---------------------------------------------------------------------------- */ Example Server
53
Client/Server Programming main (argc, argv) int argc; char *argv[]; { struct hostent *ptrh; /* pointer to a host table entry */ struct protoent *ptrp; /* pointer to a protocol table entry */ struct sockaddr_in sad; /* structure to hold server's address */ struct sockaddr_in cad; /* structure to hold client's address */ int sd, sd2; /* socket descriptors */ int port; /* protocol port number */ int alen; /* length of address */ char buf[1000]; /* buffer for string the server sends */ memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */ sad.sin_family = AF_INET; /* set family to Internet */ sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address */ Example Server
54
Client/Server Programming /* Check command-line argument for protocol port and extract */ /* port number if one is specfied. Otherwise, use the default */ /* port value given by constant PROTOPORT */ if (argc > 1) { /* if argument specified */ port = atoi (argv[1]); /* convert argument to binary*/ } else { port = PROTOPORT; /* use default port number */ } if (port > 0) /* test for illegal value */ sad.sin_port = htons((u_short)port); else { /* print error message and exit */ fprintf (stderr, "bad port number %s/n",argv[1]); exit (1); } Example Server
55
Client/Server Programming /* Map TCP transport protocol name to protocol number */ if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) { fprintf(stderr, "cannot map \"tcp\" to protocol number"); exit (1); } /* Create a socket */ sd = socket (PF_INET, SOCK_STREAM, ptrp->p_proto); if (sd < 0) { fprintf(stderr, "socket creation failed\n"); exit(1); } Example Server
56
Client/Server Programming /* Bind a local address to the socket */ if (bind(sd, (struct sockaddr *)&sad, sizeof (sad)) < 0) { fprintf(stderr,"bind failed\n"); exit(1); } /* Specify a size of request queue */ if (listen(sd, QLEN) < 0) { fprintf(stderr,"listen failed\n"); exit(1); } Example Server
57
Client/Server Programming /* Main server loop - accept and handle requests */ printf("Server up and running.\n"); while (1) { alen = sizeof(cad); fprintf( stderr, "SERVER: Waiting for contact...\n"); if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) { fprintf(stderr, "accept failed\n"); exit (1); } visits++; sprintf(buf,"This server has been contacted %d time%s\n", visits, visits==1?".":"s."); printf("SERVER: %s", buf); send(sd2,buf,strlen(buf),0); closesocket (sd2); } Example Server
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.