简体   繁体   中英

Get ip address of client from the server

I'm trying to get the ip address of each of my clients that connect to my server. I save this into fields of a struct which I sent to a thread. I'm noticing that sometimes I get the right ip and sometimes the wrong one. My first peer to connect usually has an incorrect ip...

From http://linux.die.net/man/3/inet_ntoa :

The inet_ntoa() function converts the Internet host address in, given in network byte order, to a string in IPv4 dotted-decimal notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.

Emphasis added.

The problem is that inet_ntoa() returns a pointer to static memory that is overwritten each time you call inet_ntoa() . You need to make a copy of the data before calling inet_ntoa() again:

struct peerInfo{
    char ip[16];
    int socket;
};  

while((newsockfd = accept(sockfd,(struct sockaddr *)&clt_addr, &addrlen)) > 0)
{
    struct peerInfo *p = (struct peerInfo *) malloc(sizeof(struct peerInfo));

    strncpy(p->ip, inet_ntoa(clt_addr.sin_addr), 16);
    p->socket = newsockfd;

    printf("A peer connection was accepted from %s:%hu\n", p->ip, ntohs(clt_addr.sin_port));

    if (pthread_create(&thread_id , NULL, peer_handler, (void*)p) < 0)
    {
        syserr("could not create thread\n");
        free(p);
        return 1;
    }

    printf("Thread created for the peer.\n");
    pthread_detach(thread_id);
}

if (newsockfd < 0)
{
    syserr("Accept failed.\n");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM