从服务器获取客户端的ip地址

Get ip address of client from the server

我正在尝试获取连接到我的服务器的每个客户端的 IP 地址。我将其保存到发送到线程的结构的字段中。我注意到有时我得到正确的 ip,有时是错误的。我的第一个连接点通常有一个不正确的 ip...

来自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.

添加了重点。

问题是 inet_ntoa() returns 指向静态内存的指针,每次调用 inet_ntoa() 时都会被覆盖。您需要在再次调用 inet_ntoa() 之前复制数据:

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");
}