C socket get IP address from filedescriptor returned from accept

后端 未结 3 836
独厮守ぢ
独厮守ぢ 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:16

    Statefull connection is uniquely identified by two end points Peer(address:port)<=>My(address:port). Both getpeername() and getsockname() are needed to get this information.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-02 08:32

    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

    0 讨论(0)
提交回复
热议问题