首页 文章

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

提问于
浏览
1

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

但是,sendto和recvfrom都失败了“Bad File Descriptor”,我无法弄清楚原因 .

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);

}

2 回答

  • 1

    我看到一些错误/问题:

    • 您似乎永远不会将 n 设置为文件的长度

    • 没有内存分配来保存文件

    • 一次读取一个字节的文件将非常无效

    • 加载文件后你应该知道文件的长度,不需要使用 strlen()

    • 如果文件是二进制文件, strlen() 将失败,因为它将在第一个嵌入字节处停止,值为0

  • 4

    没有输出,它有点难,但我注意到的第一件事是你从未分配缓冲区来写入文件 .

相关问题