The server normally waits on a known address for service requests. The server remains inactive until a client sends a connection request to the address of the server. The server then "awakes" and serves the client by executing the relevant actions for the client request. The server is accessed via the known Internet address. Programming of the main program loop is shown in the following example.
The server uses the following socket or POSIX interface functions in the example program:
socket(): create socket
bind(): assign a socket a name
listen(): “listen” to a socket for connection requests
accept(): accept a connection on a socket
recv(): read data from a socket
close(): close socket
Example: connection-oriented server
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define TESTPORT 2222 #define ERROR_EXIT(M) perror(M); exit(1) int main(int argc, char **argv) { int sock, length; struct sockaddr_in server; int msgsock; char buf[1024]; int rval; /* Create socket */ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { ERROR_EXIT("Create stream socket"); } /* Assign the socket a name */ server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(TESTPORT); if (bind(sock, (struct sockaddr *)&server, sizeof (server) ) < 0) { ERROR_EXIT("Bind stream socket"); } /* Start acceptance of connection requests */ listen(sock, 5); if ((msgsock = accept(sock, (struct sockaddr *)0, NULL)) < 0) { ERROR_EXIT("Accept connection"); } else do { memset(buf, 0, sizeof buf); if ((rval = recv(msgsock, buf, 1024, 0)) < 0) { ERROR_EXIT("Reading stream message"); } else if (rval == 0) { fprintf(stderr, "Ending connection\n"); } else { fprintf(stdout, "->%s\n",buf); } } while (rval != 0); close(msgsock); close(sock); return 0; }
The server uses the socket() function to create a communications endpoint (socket) and the corresponding descriptor. The server socket is assigned a defined port number with the bind() function. It can then be addressed in the network via this port number.
With the listen() function, the server determines that the socket can accept connection requests. The server accepts connection requests with accept(). The value returned by accept() is tested to ensure that the connection was successfully set up. As soon as the connection is set up, data is read from the socket with the recv() function. The server closes the socket with the close() function.
The example program is only valid for the communications domain AF_INET. If it is modified according to the information in the sections "Socket addressing" and "Creating a socket", it is also valid for the AF_INET6 domain.