570 likes | 822 Views
Client/Server Programming Using BSD Sockets. Short Presentation by Amy Apon. Client/Server Programming Outline. What is a socket and what are the two types? The layered network model Client/server model and types of servers Internet addressing Basic socket calls Sample client and server.
E N D
Client/Server ProgrammingUsing BSD Sockets Short Presentation by Amy Apon
Client/Server ProgrammingOutline • What is a socket and what are the two types? • The layered network model • Client/server model and types of servers • Internet addressing • Basic socket calls • Sample client and server 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 it • read/write or send/recv • close it Client/Server Programming Sockets
Two Types of Sockets • Stream sockets (a.k.a., TCP) • Datagram sockets (a.k.a., UDP) The sockets library that we will use is actually very flexible, and supports many types of communication Client/Server Programming Sockets
TCP Sockets TCP = Transmission Control Protocol • reliable, connection-oriented • two-way connection • messages sent in order arrive in order • like the telephone system Client/Server Programming Sockets
TCP Sockets • A connection must be established between the sender and the receiver • A conversation takes place • The connection must be ended Client/Server Programming Sockets
TCP Sockets Applications • FTP = File Transfer Protocol • HTTP = HyperText Transfer Protocol • SMTP = Simple Mail Transfer Protocol . . . are all built over TCP Client/Server Programming Sockets
The top half of TCP/IP IP = Internet Protocol • is the protocol that ties all computers (devices) on the Internet together • TCP is a transport layer protocol built over IP Client/Server Programming Sockets
UDP Sockets UDP = User Datagram Protocol • connectionless, unreliable • communication is not guaranteed to arrive, and may not arrive in order • like the post office Client/Server Programming Sockets
UDP Sockets • Don’t require set up or tear down of a connection • Generally used for packet-by-packet transfers of information • UDP applications include TFTP, BOOTP Client/Server Programming Sockets
User Datagram Protocol • UDP 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!) Client/Server Programming Sockets
The Layered Network Model Application (e.g., FTP, HTTP, telnet) Transport (e.g., TCP, UDP) Network (e.g., IP) Data Link (e.g., Ethernet) Physical (e.g., cables, etc.) Client/Server Programming Network Model
When a message is sent • The application constructs a message user data Client/Server Programming Network Model
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 layer TCP user data Client/Server Programming Network Model
An IP packet When a message is sent • The network layer adds a header IP TCP user data Client/Server Programming Network Model
An Ethernet frame When a message is sent • The data link layer adds a header, and the frame is sent out on the network Ethernet IP TCP user data Client/Server Programming Network Model
Message arrives to user memory and the application is notified Message arrives to user memory and the application is notified Message arrives to user memory and the application is notified You only see the communication at THIS LEVEL Message is copied to kernel and TCP/IP and Ethernet headers are added Message is copied to kernel and TCP/IP and Ethernet headers are stripped Message is sent onto network to receiver When a message is sent Application builds message in user memory Client/Server Programming Network Model
Client/Server Model Server Client Starts first Waits for contact from a client Responds to requests Starts second Contacts a server with a request Waits for response from server Client/Server Programming Client/Server Model
Types of Servers A server can be: Iterative Concurrent iterative stateful concurrent stateful Stateful iterative stateless concurrent stateless Stateless Client/Server Programming Types of Servers
Stateful Server • Maintains some information between requests • Requires smaller messages, since some information is kept between contacts • May become confused if a connection terminates abnormally (if the design is not fault tolerant) • Example: FTP Client/Server Programming Types of Servers
Stateless Server • Requires larger messages. That is, the message must contain all information about the request since no state information is kept. • Example: HTTP Client/Server Programming Types of Servers
Iterative Server while (1) { accept a connection (or request) from a client service the client close the connection (if necessary) } Client/Server Programming Types of Servers
Concurrent Server while (1) { accept a connection/request from client start a new thread to handle this client /* the thread must close the connection! */ } Client/Server Programming Types of Servers
Internet Addressing • Suppose you type: http://comp.uark.edu/~aapon • This invokes the HTTP protocol (over TCP/IP), and the computer “comp.uark.edu” is sent a message Client/Server Programming Addressing
Internet Addressing Find the home page of user aapon http://comp.uark.edu/~aapon/ • Same as IP address 130.184.252.197 Contact the HTTP server on the computer named comp.uark.edu Client/Server Programming Addressing
Internet Addressing • A 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. • Some IP names and addresses can also be stored in /etc/hostfile Client/Server Programming Addressing
Internet Addressing “http” says: send the message to port 80 • An IP address includes both a host address and a port number! • The HTTP server listens to port 80 • The HTTP server responds when a client contacts it Client/Server Programming Addressing
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. • Well-known ports include FTP, Telnet, SMTP, etc. Client/Server Programming Addressing
Basic Socket Calls • struct sockaddr, htons • Server calls: socket, bind, listen, accept, recv, send, close • Client calls: socket, connect, send, recv, close • gethostbyname, getprotobyname Client/Server Programming Socket Calls
A Socket Descriptor • just an int int sd; It will point to a socket structure in memory Client/Server Programming Socket Calls
Create a 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) domain type protocol Client/Server Programming Socket Calls
Socket Address Structure struct sockaddr { unsigned short sa_family; char sa_data[14]; }; address family AF_INET 14 bytes of protocol address Client/Server Programming Socket Calls
Socket Address for Internet struct sockaddr_in { /* for convenience */ short int sin_family; unsigned short int sin_port; /* 2 bytes */ struct in_addr sin_addr;/* 4 bytes */ unsigned char sin_zero[8]; }; Client/Server Programming Socket Calls
Watch out for Endians! • The sin_port and sin_address must be in Network Byte Order, which is (possibly) different from Host Byte Order • Conversion routines include: • htons - “Host to Network Short” • htonl - “Host to Network Long” Also ntohs and ntohl Client/Server Programming Socket Calls
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)); descriptor typecast size of the address Client/Server Programming Socket Calls
Bind() • Finishes filling the socket structure with address and port information in the server • Specifies the port that the server will listen to • Largest port allowed is 65535 Client/Server Programming Socket Calls
The Server Calls listen() #define QLEN 6 listen(sd, QLEN); maximum number of requests that can be queued socket descriptor Listen is NOT a blocking call! Client/Server Programming Socket Calls
The Server Calls accept() accept() is a blocking call! sin_size = sizeof(struct sockaddr_in); 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 Client/Server Programming Socket Calls
A Typical Iterative Server socket(); bind(); listen(); while(1) { accept(); /* do some work with the client */ close(); } Block here, waiting for a connection! Client/Server Programming Socket Calls
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)); Client/Server Programming Socket Calls
Sending char *msg = “Amy was here!"; int len, bytes_sent; len = strlen(msg); bytes_sent = send(sd, msg, len, 0); flags Client/Server Programming Socket Calls
Receiving Stream Sockets numbytes = recv(sd, buf, BUFSIZE, 0); while(numbytes>0) { buf[numbytes] = ‘\0’; printf(“%s”, buf); numbytes = recv(sd, buf, BUFSIZE, 0); } Client/Server Programming Socket Calls
Close the Socket close(sd); • Closes the open socket • Frees memory and allows the socket descriptor to be re-used for a different socket Client/Server Programming Socket Calls
Utility Functions • Gethostbyname() • Does a DNS call, if necessary. Converts an IP name to an IP address • Getprotobyname() • Returns a pointer to a protocol table entry, to be sure that TCP (or UCP) is known Client/Server Programming Socket Calls
/* 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 <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <string.h> #define closesocket close #define PROTOPORT 5193 /* default protocol port number */ Client/Server Programming Example Client
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. * *--------------------------------------------------------------------- */ Client/Server Programming Example Client
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 */ Client/Server Programming Example Client
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); } Client/Server Programming Example Client
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); } Client/Server Programming Example Client
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); } Client/Server Programming Example Client