gpt4 book ai didi

c - 错误的文件描述符 - 简单的 UDP 客户端

转载 作者:太空宇宙 更新时间:2023-11-04 01:14:31 24 4
gpt4 key购买 nike

当尝试创建一个简单的 UDP 客户端时,我的代码成功地打开了套接字,并从一个文件中读取了一个小缓冲区,该文件将被发送到由命令行参数指定的主机地址和端口号的服务器。

但是,sendto 和 recvfrom 都因“文件描述符错误”而失败,我不明白为什么。

void main(int argc, char* argv[]){
int s, n=0, obytes, inbytes;
struct sockaddr_in sin;
char *buffer;
int address = 0;

//Checks socket
if((s = socket(AF_INET, SOCK_DGRAM, 0))<0) {
printf("Error creating socket\n");
exit(0);
}
//Resets values in socket structure
memset((char*)&sin, 0, sizeof(sin));
sin.sin_port = htons(atoi(argv[2]));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(argv[1]);
printf("%d\n", sin.sin_addr.s_addr);
/*Opens file to be sent and reads into buffer*/
FILE *readFile;
readFile = fopen(argv[3], "r");
//Checks if file to be read can be opened
if (readFile==NULL) {
perror ("Error opening file");
}
//Reads in all the characters to a buffer
else{
while (!feof(readFile)) {
buffer[n] = fgetc (readFile);
n++;
}

buffer[n] = '\0';
printf ("Total number of bytes: %d\n", n);
for(int i = 0; i< n; i++){
printf("%c", buffer[i]);
}
}
printf("File was opened\n");
//Sends the buffer to the destination designated by the socket structure and checks to see if bytes were sent
if((obytes = sendto(s, buffer, strlen(buffer), 0, (struct sockaddr *)&sin, sizeof(sin))) == -1 ) {
perror("Sendto() error!");
exit(1);
}
printf("%d bytes were sent\n",obytes);
//Receives response from the server and checks to see if bytes were actually received
/* if((inbytes = recvfrom(s, buffer, strlen(buffer)+28, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr*))) == -1 ) {
perror("Recvfrom() error!");
exit(1);
}*/
printf("%d bytes were received.\n", inbytes);
//Closes file
fclose (readFile);

}

最佳答案

我看到一些错误/问题:

  • 你似乎从来没有将n设置为文件的长度
  • 没有内存分配来保存文件
  • 一次一个字节地读取一个文件是非常低效的
  • 加载文件后,您应该知道文件的长度,无需使用strlen()
  • 如果文件是二进制文件,strlen() 将失败,因为它将在第一个值为 0 的嵌入字节处停止

关于c - 错误的文件描述符 - 简单的 UDP 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4843930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com