Devember: Get the local address

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

Devember: Get the local address

Yesterday, we have seen how the server can retrieve the client address. Let’s see today how an host can get the local address through the getsockname function.

struct sockaddr_in6 cliaddr;
socklen_t clilen = sizeof(cliaddr);
bzero(&cliaddr, clilen);
if (getsockname(sockfd, (struct sockaddr *) &cliaddr, &clilen) < 0) {
    return -1;

Then we convert the IPv6 address and port into the appropriate host representation and can print:

char clistr[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &cliaddr.sin6_addr, clistr, INET6_ADDRSTRLEN);
printf("The current address is %s:%d\n", clistr, ntohs(cliaddr.sin6_port));

The complete code can be found on this repository.

3 December 2015