我正在尝试编写井字游戏通过 UDP 进行通信。现在我有代码:
int recv_txt(int sock, struct sockaddr_in *incoming_addr)
{
char bud[MAX_LENGTH];
unsigned int incoming_add_len;
incoming_add_len = sizeof(*incoming_addr);
if(recvfrom(sock, &buf, MAX_LENGTH, 0 (struct sockaddr*)incoming_addr, &incoming_addr_len) < 0)
{
return 0;
}
printf("received %s", buf);
return 1;
}
int main(int argv, char **argc)
{
/** some code to create socket etc */
struct sockaddr_in incoming_addr;
for(;;)
{
recv_txt(sock, &incoming_addr);
//here I would like to create new thread, which will process the buffer from recv_txt and send response;
}
}
现在我需要从中获取缓冲区recv_txt
,将其放入如下结构中:
struct M_s
{
struct sockaddr_in address;
char[MAX_LENGTH] buffer;
}
并将其传递给新线程。但我无法从中获取缓冲区recv_txt
。我在 C 中很新,现在我不能很好地使用指针。
感谢您的任何建议。
编辑
我尝试了 Frankie_c 提供的解决方案,但我printf
现在遇到了问题。当我尝试main
:
LP_ARGS_STRUCT args = recv_txt(sock)
printf("data from: %s", inet_ntoa(args->address.sin_adrr))
我没有得到任何打印到控制台或收到错误消息。
EDIT2 - 完整代码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define SRV_PORT 23456
#define MAX_TXT_LENGTH 1000
#define MAX_ROOMS 1
int sock;
typedef struct args_s
{
struct sockaddr_in address;
char buffer[MAX_TXT_LENGTH];
} ARGS_STRUCT, *LP_ARGS_STRUCT;
//typedef struct args_s args;
LP_ARGS_STRUCT recv_txt(int sock)
{
LP_ARGS_STRUCT args = malloc(sizeof(ARGS_STRUCT));
//memory error
if(!args)
{
return 1;
}
unsigned int incoming_addr_len = sizeof(args->address);
//incoming_addr_len = sizeof(*incoming_addr);
if (recvfrom(sock, &args->buffer, MAX_TXT_LENGTH, 0,
(struct sockaddr*)&args->address, &incoming_addr_len) < 0)
{
free(args);
return NULL;
}
printf("received: %s %s\n", args->buffer, inet_ntoa(args->address.sin_addr));
return 1;
}
int main(int argv, char **argc)
{
int i = 0;
int optval;
struct sockaddr_in addr, incoming_addr;
char buffer[MAX_TXT_LENGTH];
/* create socket */
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock < 0)
{
err("socket()");
}
/* set reusable flag */
optval = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
/* prepare inet address */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(SRV_PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY); /* listen on all interfaces */
if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
{
err("bind");
}
for(;;)
{
LP_ARGS_STRUCT args = recv_txt(sock);
if(!args) continue;
printf("%s\n", args->buffer);
}
return 0;
}
收到一个数据包后,我得到:
received: Hello 192.168.56.1
Segmentation fault (code dumped)
Process returned 139 (0x8B)