I know this question seems typical and multiple times answered but I think if you read the details it is not so common (I did not find it).
The poin
Ok. Thanks to @alk and @rileyberton I found the correct method to use, the getpeername:
int sockfd;
void main(void) {
//[...]
struct sockaddr_in clientaddr;
socklen_t clientaddr_size = sizeof(clientaddr);
int newfd = accept(sockfd, (struct sockaddr *)&clientaddr, &clientaddr_size);
//fork() and other code
foo(newfd);
//[...]
}
void foo(int newfd) {
//[...]
struct sockaddr_in addr;
socklen_t addr_size = sizeof(struct sockaddr_in);
int res = getpeername(newfd, (struct sockaddr *)&addr, &addr_size);
char *clientip = new char[20];
strcpy(clientip, inet_ntoa(addr.sin_addr));
//[...]
}
So now in a different process I can get the IP address (in the "string" clientip
) of the client that originated the connection only carrying the file descriptor newfd
obtained with the accept method.