You are here

TutorialLibraryTest ApplicationDownload
[Tutorial]LibraryTest ApplicationDownload

Error message

Deprecated function: The each() function is deprecated. This message will be suppressed on further calls in menu_set_active_trail() (line 2404 of /home/quantics/public_html/dp/includes/

Socket Tutorial

Chapter 8 - Getting a server listening

C_SCP::Listen (bool state, unsigned int maxWaiting, unsigned int port)

This function enables listening with a C_SCP object. Parameter state can start it or stop it. Parameter mawWaiting determines the number of customers who may be simultaneously waiting for connection acceptance. Parameter port specifies the port on which the server must listen to.

The code begins by initializing some parameters and structures. sa is the address of the local machine. It is first initialized with zeros by the function memset. hp is a structure that will contain information on the local machine.

struct sockaddr_in sa;
struct hostent *hp;
char name [400 +1];
int result;

memset (&sa, 0, sizeof (sockaddr_in));

First, function gethostname enables to retrieve the local machine name. Then, function gethostbyname enables to retrieve network parameters of the machine given in argument (ie the local machine) and to write them into the structure hp.

int r = gethostname (name, 400);


hp = gethostbyname (name);

The address with which our listening socket listenSock is bound has to be built (sa). The important parameters are the type of address (which is read in the structure hp) and the port number on which to listen.

sa.sin_family = hp->h_addrtype;
sa.sin_port = htons (port);

The listening socket listenSock can then be created tanks to function socket, by specifying that the address type is IP v4 (AF_INET) and the protocol is TCP (SOCK_STREAM). Once created, the socket can be bound to the address buit above (sa). Notice how sa, a sockaddr_in structure, is casted into a sockaddr structure, which is the argument type expected by function bind. The equivalent operation on objects is called polymorphism.

listenSock = socket (AF_INET, SOCK_STREAM, 0);


result = bind (listenSock, (struct sockaddr *) &sa, sizeof (struct sockaddr_in));

Finally, listening is enabled on the socket with function listen. Parameter maxWaiting specifies the maximum number of clients that can simultaneously be waiting for connection acceptance. This parameter has no relation with the maximum number of clients that can be simultaneously connected to the server.

result = listen (listenSock, maxWaiting);