Devember: Get Client informations

This post is part of the Devember collection, useful for the study of the Socket API.

Devember: Get Client informations

Previously, the Daytime Server invoked the accept function in this way:

accept(listenfd, (struct sockaddr *) NULL, NULL);

We could use this function in all its power by passing as an argument a sockaddr structure which will be filled with informations about the client:

struct sockaddr_in6 cliaddr;
socklen_t clilen;
clilen = sizeof(cliaddr);
bzero(&cliaddr, clilen);
accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);

Remember, you can not print the address and port before you convert these informations into the appropriate host representation:

inet_ntop(AF_INET6, &cliaddr.sin6_addr, buff, INET6_ADDRSTRLEN);
printf("Serving new client from %s:%d\n", buff, ntohs(cliaddr.sin6_port));

The complete code can be found on this repository.

2 December 2015