我试图使用macOS函数在sendfile()上编写一个简单的FTP类客户端服务器网络程序.在阅读了苹果公司关于这个主题的开发者手册之后,遗憾的是,我仍然很难使用它。
代码
// creation of fd
int fd = open("file_path", O_RDONLY);
off_t len = 0;
// the creation of sockets used in sendfile
getaddrinfo(NULL, port, &hints, &servinfo);
// p is iterating through servinfo (p=p->ai_next)
sockfd= socket(p->ai_family, p->ai_socktype, p->ai_protocol);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
bind(sockfd, p->ai_addr, p->ai_addrlen);
listen(sockfd, BACKLOG); //BACKLOG is a macro configuring pending connections
new_sockfd = accept(sockfd, (struct sockaddr*)&clients_addr, &sin_size);
// sendfile
if(sendfile(new_sockfd, fd, 0, &len, NULL, 0)==-1){
fprintf(stderr, "server sendfile errno: %d", errno);
// sorry I know this is not the best way to interpret the errno
}当errno代码被设置为45时,客户端收到一条消息“对等端关闭了连接”;
我已经检查了文件描述符fd使用read()并打印出来,它运行良好;
发布于 2021-11-16 15:42:53
你把论点倒过来了。根据文献资料,错误代码ENOTSUP (我认为它是“不支持的操作”)--感谢Jeremy查找它--您应该打印strerror(errno),因为它很有用)意味着fd不是一个常规文件。
fd是第一个论点。
int sendfile(int fd, int s, off_t offset, off_t *len, struct sf_hdtr *hdtr, int flags);sendfile()系统调用将由描述符fd指定的常规文件发送给描述符s指定的流套接字。
因此,您的代码没有试图通过套接字发送文件。它试图通过文件发送套接字,这是没有意义的。改变命令。
https://stackoverflow.com/questions/69990609
复制相似问题