The getsockname() function retrieves the local address associated with a socket.

my_addr_size = sizeof my_addr;
if (getsockname(sockfd, (struct sockaddr *) &my_addr, &my_addr_size) == -1) {
     perror("getsockname");
     goto close;
}