【发布时间】:2009-05-28 10:01:18
【问题描述】:
我发现了一个很好的抽象,我可以使用 FILE 从 UDP 读取数据。这非常适合读取数据,但我无法让它通过 UDP 吐出数据。下面是通过 FILE 流读取 UDP 数据的代码:
u_int8 *buf;
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in serverAddr;
if (sockfd < 0) {
printf("Could not open socket\n");
exit(1);
}
buf = malloc(BUF_SIZE * sizeof(u_int8));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(port);
int rc = bind(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
if (rc<0) {
printf("Could not bind to port %d\n", port);
exit(1);
}
/* Make sockfd blocking */
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags & ~O_NONBLOCK);
FILE *sockfile;
sockfile = (FILE*)fdopen(sockfd, "r");
现在一些其他代码可以调用:
fread(data, sizeof(u_int8), frame_payload_size, sockfile);
这很好用。但是,相反的情况似乎并非如此:
u_int8 *buf;
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in clientAddr;
if (sockfd < 0) {
printf("Could not open socket\n");
exit(1);
}
memset((char *)&clientAddr, 0, sizeof(clientAddr));
buf = malloc(BUF_SIZE * sizeof(u_int8));
clientAddr.sin_family = AF_INET;
clientAddr.sin_port = htons(port);
if (inet_aton("127.0.0.1", &clientAddr.sin_addr)==0) {
printf("inet_aton()\n");
abort();
}
int rc = bind(sockfd, (struct sockaddr *)&clientAddr, sizeof(clientAddr));
FILE *sockfile;
sockfile = (FILE*)fdopen(sockfd, "w");
其他一些代码会调用:
written = fwrite(fm->frame, sizeof(u_int8), fm->frame_length, data_out_stream);
'written' 将返回写入的正数元素,但似乎没有生成 UDP 数据包。
我正在尝试做的事情可能吗?关于为什么它可能不起作用的任何建议?
【问题讨论】: