C socket get IP address from filedescriptor returned from accept

后端 未结 3 835
独厮守ぢ
独厮守ぢ 2021-01-02 07:26

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 08:25

    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.

提交回复
热议问题