我发现了一个很好的抽象,我可以使用FILE从UDP读取数据。这对于读取数据非常有用,但是我无法通过UDP来传递数据。下面是在文件流的UDP数据读取的代码为:使用FILE流在c中读取/写入套接字
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);
“写”将返回写入元素的正数,但没有UDP数据包似乎产生。
正在尝试做什么?任何建议,为什么它可能不工作?