C socket get IP address from filedescriptor returned from accept

混江龙づ霸主 提交于 2019-11-29 19:09:35

问题


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 point 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 treat it, so there can be multiple connections opened at the same time.

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

Later on (after and inside some other methods and code) the child process save the connection information to the BBDD and I need also, in that precise moment, to get the IP address that opened that connection being treated.

As there can be multiple connections at the same time and the variable struct sockaddr_in clientaddr that I pass to the accept method is shared for all the process I am not sure that later on is a good idea to get the IP address information from that way because then I could get the IP address from another connection opened.

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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/20472072/c-socket-get-ip-address-from-filedescriptor-returned-from-accept

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!