Sockets 从服务器获取客户端的ip地址
我正在尝试获取连接到服务器的每个客户端的ip地址。我将其保存到发送到线程的结构的字段中。我注意到有时我得到了正确的ip,有时是错误的ip。我的第一个连接的对等方通常具有不正确的ip…来自: 函数的作用是:将给定的Internet主机地址转换为 按网络字节顺序,转换为点十进制表示法的字符串。 字符串在静态分配的缓冲区中返回,该缓冲区 后续呼叫将覆盖。Sockets 从服务器获取客户端的ip地址,sockets,struct,ip-address,Sockets,Struct,Ip Address,我正在尝试获取连接到服务器的每个客户端的ip地址。我将其保存到发送到线程的结构的字段中。我注意到有时我得到了正确的ip,有时是错误的ip。我的第一个连接的对等方通常具有不正确的ip…来自: 函数的作用是:将给定的Internet主机地址转换为 按网络字节顺序,转换为点十进制表示法的字符串。 字符串在静态分配的缓冲区中返回,该缓冲区 后续呼叫将覆盖。 重点已添加。问题在于inet\u ntoa()返回指向静态内存的指针,每次调用inet\u ntoa()时,该指针都会被覆盖。再次调用inet\u
重点已添加。问题在于
inet\u ntoa()
返回指向静态内存的指针,每次调用inet\u ntoa()
时,该指针都会被覆盖。再次调用inet\u 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");
}
struct peerInfo{
char-ip[16];
int插座;
};
而((newsockfd=accept(sockfd,(struct sockaddr*)&clt_addr,&addrlen))>0)
{
结构peerInfo*p=(结构peerInfo*)malloc(sizeof(结构peerInfo));
strncpy(p->ip,inet_ntoa(clt_addr.sin_addr),16);
p->socket=newsockfd;
printf(“接受了来自%s:%hu\n”、p->ip、ntohs(clt_addr.sinu port)的对等连接);
if(pthread_create(&thread_id,NULL,peer_handler,(void*)p)<0)
{
syserr(“无法创建线程\n”);
自由基(p);
返回1;
}
printf(“为对等方创建的线程。\n”);
pthread_detach(线程id);
}
if(newsockfd<0)
{
syserr(“接受失败。\n”);
}
换句话说,您需要复制inet_ntoa()
返回的数据,您无法将返回的指针保存为原样。是否应该将内存分配给p->ip?它已经存在了。在我的示例中,ip
是一个固定长度的数组。调用malloc()
时,它包含在peerInfo
的完整大小中。