从服务器获取客户端的IP地址
问题描述:
我试图获取连接到我的服务器的每个客户端的IP地址。我将其保存到我发送给线程的结构的字段中。我注意到,有时我得到正确的IP,有时候是错误的。我的第一个通常连接同行中有一个不正确的IP ...从服务器获取客户端的IP地址
答
问题是inet_ntoa()
返回一个指向静态内存的指针,每次调用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");
}
答
http://linux.die.net/man/3/inet_ntoa从:
的INET_NTOA()函数将在Internet上的主机地址,在网络字节顺序给出 ,在IPv4中的字符串点分十进制表示法。 该字符串在静态分配的缓冲区中返回,后续调用将被覆盖。
强调添加。
+0
换句话说,你需要使数据的副本'INET_NTOA()'的回报,你不能保存返回的指针,是。 –
应该将内存分配给p-> ip? – coder4lyf
它已经是。在我的例子中,'ip'是一个固定长度的数组。调用'malloc()'时,它包含在'peerInfo'的全部大小中。 –