C socket gets the IP address from filedescriptor returned from accept

I know this question seems typical and answered several times, but I think that if you read the details, this is not so often (I did not find it).

The fact is that I am developing a unix service in c that opens a socket and waits for connections, when I have a connection I create a new process to handle it , so there can be several connections open simultaneously .

int newfd = accept(sockfd, (struct sockaddr *)&clientaddr, (socklen_t*)&clientaddr_size); 

Later ( after and inside some other methods and code) the child process save the connection information with BBDD, and I also need at this exact moment to get the IP address that opened the processed connection.

There can be several connections at the same time , and the struct sockaddr_in clientaddr variable that I pass to the accept method is used for the whole process. I'm not sure that later it is a good idea to get information about the IP address from this path, because then I could get IP address from another open connection .

I would like to be able to access the IP address from the file descriptor of the int newfd file that I get from the accept method (return integer). Is it possible? Or did I misunderstand the file descriptor function?

+8
c unix file-descriptor fork sockets
source share
2 answers

Ok Thanks to @alk and @rileyberton, I found the correct method to use, 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 another process, I can get the IP address (in the " clientip " clientip ) of the client who initiated the connection, only carrying the newfd file descriptor obtained using the accept method.

+12
source share

You must use getsockname() ( http://linux.die.net/man/2/getsockname ) to get the IP address of the associated socket.

Also answered earlier: C - Public IP address from file descriptor

+3
source share

All Articles