C socket get IP address from filedescriptor returned from accept
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.
You would use getsockname()
(http://linux.die.net/man/2/getsockname) to get the IP of the bound socket.
Also answered before, here: C - Public IP from file descriptor